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;
}
}