1. 引入jar
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
2. 配置application.xml文件
# SpringBoot配置文件敏感信息加密-jasypt
jasypt:
encryptor:
#加密秘钥 - 自定义
password: 123456
#指定解密算法(默认)
algorithm: PBEWithMD5AndDES
# 3.0.0版本及以上版本需要添加如下配置
iv-generator-classname: org.jasypt.iv.NoIvGenerator
3. 加密串
3.1 maven下载jar包,jasypt-1.9.2.jar,自行下载
3.2 秘钥123456,获取root密文
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=123456 algorithm=PBEWithMD5AndDES input=root
4. 把加密好的密文写入到xml配置文件,默认格式:ENC(),格式可以自定义自己喜欢的,自行扩展
spring.datasource.username: ENC(rIIKhbVXJ0JDTAzafPPqYQ==)
补充 : 如果你用的是3.0版本以上或者以上的出现如下报错
Failed to bind properties under 'spring.datasource.username' to java.lang.String
这是数据库用户名没有解密导致的,在github上ulisesbocchio 的https://github.com/ulisesbocchio/jasypt-spring-boot 的README.md 中有一条
把iv-generator-classname: org.jasypt.iv.NoIvGenerator加在后面问题即可解决
总结 : 线上部署可以把秘钥写入到环境变量,这样就不需要在配置文件中获取秘钥,提高安全性,避免被反解密,格式如下:
#打开/etc/profile文件
vim /etc/profile
#插入
export JASYPT_PASSWORD = 123456
#编译
source /etc/profile
#运行_1
java -jar -Djasypt.encryptor.password=${JASYPT_PASSWORD} xxx.jar
#运行_2
nohup java -jar -Djasypt.encryptor.password=${JASYPT_PASSWORD} xxx.jar
>catalina.out 2>&1 &
#运行_3(未设置环境变量)
java -jar -Djasypt.encryptor.password=123456 xxx.jar