1、 添加依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2、生成明文的密文串
@Test
public void encrypt() {
String password = "123456abc"; // 原明文密码(待加密)
String salt = "salt"; // 用于要加密的口令(保护好)
String[] arg = {"input=" + password, "password=" + salt, "algorithm=PBEWithMD5AndDES", "ivGeneratorClassName=org.jasypt.iv.NoIvGenerator"};
JasyptPBEStringEncryptionCLI.main(arg);
}
OUTPUT:
MnGfUY6+XB84m7YxEeq5JHLJFyI1iCQd
里的串即为密文,每次加密出来的结果都不一样,但解密后一样。
3、配置文件修改
将原密码替换成:ENC(密文串)
这种格式
spring:
datasource:
username: root
password: ENC(MnGfUY6+XB84m7YxEeq5JHLJFyI1iCQd)
jasypt:
encryptor:
password: salt
注:jasypt.encryptor.password可以不配在yml里,通过spring boot 启动参数,salt
为自定义口令,需要保护好。
java -jar your-app.jar --jasypt.encryptor.password=salt
或配置一个叫jasypt.encryptor.password
的环境变量,启动时会自动读取
4、解密
知道密文串、口令、加密算法,是可以解密的,所以要保护好这三个值,解密:
@Test
public void decrypt() {
String cypherString = "MnGfUY6+XB84m7YxEeq5JHLJFyI1iCQd"; // 原明文密码(待加密)
String salt = "salt"; // 用于要解密的口令(保护好)
String[] arg = {"input=" + cypherString, "password=" + salt, "algorithm=PBEWithMD5AndDES", "ivGeneratorClassName=org.jasypt.iv.NoIvGenerator"};
JasyptPBEStringDecryptionCLI.main(arg);
}
输出:
123456abc