1、添加依赖:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.18</version>
</dependency>
2、在application.properties中添加配置:
jasypt.encryptor.algorithm=PBEWithMD5AndDES // jasypt算法
jasypt.encryptor.password=mykey // 密钥
spring.mail.username=name // 邮件账号,明文
spring.mail.password=ENC(9mXQ+BTHP1BD3EVwwwwwJVSq8BTyn) // 邮件密码 密文 (ENC 为关键字)
3、加解密工具:"
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
public class EncryptConfigUtil {
/**
* 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) {
// 加密
String encPwd = encyptPwd("mykey", "password");
// 解密
String decPwd = decyptPwd("mykey", encPwd);
System.out.println(encPwd);
System.out.println(decPwd);
}
}
转自:https://blog.csdn.net/zhou_fan_xi/article/details/108650444?utm_medium=distribute.pc_relevant.none-task-blog-title-1&spm=1001.2101.3001.4242