1.pom添加 加密依赖
<!-- 加密依赖 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
2.编写工具类
package com.jeesite.modules.utils;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 配置文件加解密工具类
* https://blog.csdn.net/qq_41617261/article/details/121448939
*/
@Component
public class JasyptUtil {
private static String password;
@Value("${jasypt.encryptor.password}")
public static void setPassword(String password) {
JasyptUtil.password = password;
}
private static final String PBEWITHMD5ANDDES = "PBEWithMD5AndDES";
private static final String PBEWITHHMACSHA512ANDAES_256 = "PBEWITHHMACSHA512ANDAES_256";
public static void main(String[] args) {
JasyptUtil.password = "+oE67TSCE/j7==";
// 加密
String username = encyptPwd("123");
String password = encyptPwd("678");
System.out.println(username);
System.out.println(password);
}
/**
* 加密方法
*
* @param value 需要加密的值
*/
public static String encyptPwd(String value) {
// 1. 创建加解密工具实例
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
// 2. 加解密配置
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(password);
config.setAlgorithm(PBEWITHMD5ANDDES);
// 3. 为减少配置文件的书写,以下都是 Jasyp 3.x 版本,配置文件默认配置
config.setKeyObtentionIterations("1000");
config.setPoolSize("1");
config.setProviderName("SunJCE");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
String result = encryptor.encrypt(value);
return result;
}
/**
* 解密方法
*
* @param value 需要解密的值
*/
public static String decryptPwd(String value) {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
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");
encryptor.setConfig(config);
String result = encryptor.decrypt(value);
return result;
}
}
3.yml文件添加必要内容
#数据库密码加密
jasypt:
encryptor:
#加密盐
password: +oE67TSCE/j7+
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
因为3.x的版本里面的加密方式默认是别的所以yml文件需要指定一下
4.
jdbc:
# Mysql 数据库配置
type: mysql
driver: com.mysql.jdbc.Driver
username: ENC(Y1dsy3NNUuDHERMyfT8jJRMNeBdg3l8U)
password: ENC(SDQcQ+7C6/6H1eO4AoTwLmrmOWc4uOhfI0MG/llr1KA=)
先用工具类把明文加密然后在填进去
密文用ENC(密文字符串) 这种类型填入