1、添加依赖
compile('com.github.ulisesbocchio:jasypt-spring-boot-starter:1.5')
2、编写加密解密工具类
/**
* TODO(这里用一句话描述这个类的作用)
*
* @className JasyptUtil
* @author Administrator
* @version V1.0 2020年3月24日 下午5:14:47 TODO(如果是修改版本,描述修改内容)
*/
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
public class JasyptUtil {
/**
* Jasypt生成加密结果
*
* @param password 配置文件中设定的加密密
* @param value 加密值
* @return
*/
public static String encyptPwd(String password, String value) {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
encryptor.setConfig(cryptor(password));
String result = encryptor.encrypt(value);
return result;
}
/**
* 解密
*
* @param password 配置文件中设定的加密密码
* @param value 解密密文
* @return
*/
public static String decyptPwd(String password, String value) {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
encryptor.setConfig(cryptor(password));
String result = encryptor.decrypt(value);
return result;
}
public static SimpleStringPBEConfig cryptor(String password) {
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(password);
config.setAlgorithm("PBEWithMD5AndDES");
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setStringOutputType("base64");
return config;
}
// public static void main(String[] args) {
// // 加密
// System.out.println(encyptPwd("neusoft", "root1234"));
// // 解密
// System.out.println(decyptPwd("neusoft",
// "VnCioJPCXOOPIOx5Aq9XuigNH6OuaOoz"));
// }
}
3、修改配置文件
配置数据库密码
spring.datasource.password=ENC(加密好的密文)
配置加密私钥
jasypt.encryptor.password=neusoft
4、需要使用的地方调用工具类解密
String password = ""; //配置文件中的秘钥
String pwd = ""; //加密后的密文
JasyptUtil.decyptPwd(password, pwd)