介绍
在 Spring Boot 项目中,使用 Druid 连接池加密 application.yml 中的数据库密码。
Druid
提供了ConfigTools
工具类来加密密码(默认使用非对称加密 RSA)。
编写工具类 DruidEncryptUtil
ts
/**
* 数据库加密util
*/
public class DruidEncryptUtil {
private static String publicKey;
private static String privateKey;
static {
try {
String[] keyPair = ConfigTools.genKeyPair(512);
privateKey = keyPair[0];
System.out.println("privateKey:" + privateKey);
publicKey = keyPair[1];
System.out.println("publicKey:" + publicKey);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
}
}
public static String encrypt(String plainText) throws Exception {
String encrypt = ConfigTools.encrypt(privateKey, plainText);
System.out.println("encrypt:" + encrypt);
return encrypt;
}
public static String decrypt(String encryptText) throws Exception {
String decrypt = ConfigTools.decrypt(publicKey, encryptText);
System.out.println("decrypt:" + decrypt);
return decrypt;
}
public static void main(String[] args) throws Exception {
String encrypt = encrypt("123"); //密码为123
}
}
输出示例:
privateKey:MIIBVgIBADANBgkqhkiG9w0BAQgE8AgEAAkEA5yD6P+Z....(私钥,需保存)
publicKey:MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOcg+j/mZ....(公钥,配置到yml)
password:PNak7fX4....(加密后的密码,配置到yml)
配置 application.yml
ts
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useSSL=false
username: root
password: PNak7fX4.... # 加密后的密码
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 配置公钥
connectionProperties: config.decrypt=true;config.decrypt.key=${publicKey};
# 启用加密配置
filters:
config:
enabled: true
# 替换为你的公钥
publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOcg+j/mZ....