一、pom文件引入jar包
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
二、新建JasyptDemo 工具类
- 设置秘钥 String KEY = "自定义秘钥";
- 两种加密算法任选一种对要加密的字符串加密
import org.jasypt.util.text.BasicTextEncryptor;
import org.jasypt.util.text.StrongTextEncryptor;
public class JasyptDemo {
public static final String KEY = "myKey";
public static void main(String[] args) {
System.out.println("username:"+pbeWithMD5AndDES("root"));
System.out.println("password:"+pbeWithMD5AndDES("123456"));
System.out.println("username:"+pbeWithMD5AndTripleDES("root"));
System.out.println("password:"+pbeWithMD5AndTripleDES("123456"));
}
/**
* PBEWithMD5AndDES加密法.
* @param key 秘钥
* @param str 要加密的字符串
* @return 加密字符串
*/
public static String pbeWithMD5AndDES(String str) {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//加密所需秘钥
textEncryptor.setPassword(KEY);
//加密
return textEncryptor.encrypt(str);
}
/**
* PBEWithMD5AndTripleDES加密法.
* @param key 秘钥
* @param str 要加密的字符串
* @return 加密字符串
*/
public static String pbeWithMD5AndTripleDES(String str) {
StrongTextEncryptor textEncryptor = new StrongTextEncryptor();
//加密所需秘钥
textEncryptor.setPassword(KEY);
//加密
return textEncryptor.encrypt(str);
}
}
看下源码:
加密后的值,每次运行加密的值都不一样不用奇怪。
username:Yr9iXBshBnTwweou9L2l+Q==
password:LihhSZSYNDIbr+7JC8b4NA==
username:DDb4utnzoa7GUznEIZ85Lg==
password:gfOTzaxPbe3MwfojkrlFGw==
三、properties文件使用加密的值
注意:!!!
使用方法:ENC(加密串)
##datasource info
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=ENC(Yr9iXBshBnTwweou9L2l+Q==)
spring.datasource.password=ENC(LihhSZSYNDIbr+7JC8b4NA==)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.primary.minimum-idle=5
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
运行时在 run conf 中配置秘钥
-Djasypt.encryptor.password=myKey
myKey是自定义的key!
四、启动jar包时 要指定自己定义的秘钥
java -jar -Djasypt.encryptor.password=myKey xxx.jar