1. 引入依赖
<!--数据库加密解密-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.14</version>
</dependency>
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>1.14</version>
</dependency>
<!--数据库加密解密结束-->
2. yml配置添加盐值
# jasypt加密的盐值
jasypt:
encryptor:
password: mykey
3. 生成加密密码
加密
public static void main(String[] args) {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES"); // 加密的算法,这个算法是默认的
config.setPassword("mykey"); // 加密的密钥(配置的盐值)
standardPBEStringEncryptor.setConfig(config);
String plainText = "root"; // 数据库的明文密码
String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
System.out.println("加密后的密码:" + encryptedText);
}
控制台输出:
加密后的密码:YBfk59LZ1JyZ+P6i2Imd/g==
4. 解密加密密码
解密
public static void main(String[] args) {
StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
EnvironmentPBEConfig config = new EnvironmentPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES"); // 解密的算法,这个算法是默认的
config.setPassword("mykey"); // 解密的密钥(配置的盐值)
standardPBEStringEncryptor.setConfig(config);
String encryptedText = "YBfk59LZ1JyZ+P6i2Imd/g=="; // 数据库的加密密码
String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
System.out.println("解密后的密码:" + plainText);
}
控制台输出:
解密后的密码:root