Nacos 使用Jasypt加密

Nacos使用Jasypt进行加密

1、引入依赖
<!-- https://mvnrepository.com/artifact/io.springboot.plugin/jasypt-spring-boot -->
<dependency>
    <groupId>io.springboot.plugin</groupId>
    <artifactId>jasypt-spring-boot</artifactId>
    <version>3.1.0</version>
</dependency>

2、 Java 加密程序:生成加密字符串

import org.jasypt.util.text.AES256TextEncryptor;

public class JasyptEncryptor {
    public static void main(String[] args) {
        AES256TextEncryptor encryptor = new AES256TextEncryptor();
        encryptor.setPassword("your_secret_password"); // 设置密钥

        // 加密,把用户加密
        String encrypted = encryptor.encrypt("root");

        System.out.println("ENC(" + encrypted + ")");

        // 解密测试
        String decrypted = encryptor.decrypt(encrypted);
        System.out.println("解密结果:" + decrypted);
    }
}

3、nacos的配置文件里的内容,用ENC(加密的串)
config:
      test2: ENC(dNhslpjccQKeAaRGaxyRo7VGPiUa0TDPRtPfsk8j3NWkrAbwn1z6aA00ud94TxFF)


4、yaml 加入
application.yml

jasypt:
  encryptor:
    password: your_secret_password # 生产环境应从安全渠道获取,设置密钥要和JasyptEncryptor类里的一致

5、启用 jasypt 解密支持,在启动类加上@EnableEncryptableProperties // 手动启用 Jasypt
在你的 Spring Boot 项目中配置密钥(jasypt 会自动解密):


import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableEncryptableProperties // 手动启用 Jasypt
public class NacosTestForSpringboot3Application {

    public static void main(String[] args) {
        SpringApplication.run(NacosTestForSpringboot3Application.class, args);
    }

}

6、测试

@RestController
public class ConfigController {

  // 引入加密的配置类
  @Value("${config.test2}")
  String rate5;

  @RequestMapping("/rate5")
  public String rate5() {
    return rate5;
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值