springboot使用jasypt完成配置文件中的脱敏
1、导入pom.xml
<!-- Jasypt加密 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
2、yml配置中引入
# 配置文件加密key
jasypt:
encryptor:
password: Lian
3、Jasypt加解密工具类
package com.example.springbootdemo;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
public class jsyptPassword {
private static final String PBEWITHMD5ANDDES = "PBEWithMD5AndDES";
private static final String PBEWITHHMACSHA512ANDAES_256 = "PBEWITHHMACSHA512ANDAES_256";
public static SimpleStringPBEConfig encryJsypt(String password){
//加解密配置
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(password);
config.setAlgorithm(PBEWITHHMACSHA512ANDAES_256);
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
config.setStringOutputType("base64");
return config;
}
public static String encryptPassword(String password, String value){
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = encryJsypt(password);
encryptor.setConfig(config);
String resutl_encrypt = encryptor.encrypt(value);
return resutl_encrypt;
}
public static String decryptPassword(String password, String value){
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = encryJsypt(password);
encryptor.setConfig(config);
String result_decrypt = encryptor.decrypt(value);
return result_decrypt;
}
public static void main(String[] args) {
//第一个参数修改记得yml中也要同步修改
String encrypt = encryptPassword("Lian", "root");
System.out.println("root加密后:" + encrypt);
String decrypt = decryptPassword("Lian", "kXRzoLJzzKjhaaZ7gq/Upy1lKKIPgE9BePJgydcXo+Qm/rc2wtEMgUPlb7yEPytv");
System.out.println("root解密后:" + decrypt);
}
}
4、yml中使用
ENC(密文)
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
username: root
password: ENC(kXRzoLJzzKjhaaZ7gq/Upy1lKKIPgE9BePJgydcXo+Qm/rc2wtEMgUPlb7yEPytv)

浙公网安备 33010602011771号