代码:
public class DruidEncryptUtils {
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) {
} catch (NoSuchProviderException e) {
throw new RuntimeException(e);
}
}
/**
* 加密
* @param plainText
* @return
* @throws Exception
*/
public static String encrypt(String plainText) throws Exception {
String encrypt = ConfigTools.encrypt(privateKey, plainText);
System.out.println("encrypt:" + encrypt);
return encrypt;
}
/**
* 解密
* @param plainText
* @return
* @throws Exception
*/
public static String decrypt(String plainText) throws Exception {
String decrypt = ConfigTools.decrypt(publicKey, plainText);
System.out.println("decrypt:" + decrypt);
return decrypt;
}
public static void main(String[] args) throws Exception {
//私钥加密数据库密码得到加密后的串
String aaa = encrypt("数据库密码");
System.out.println(aaa);
}
}
流程:先用私钥加密数据库密码,得到加密后的串,这个串填到数据库的密码位置,开启druid的解密,用公钥去进行解密。
这里需要三个串:
1.生成的公钥
2.生成的私钥
3.用私钥对密码加密后的串
配置文件代码:
spring:
datasource:
username: root
#私钥==》加密后的串,放这,通过公钥解密
password: 加密后的串
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://ip:3306/jc-club?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true
type: com.alibaba.druid.pool.DruidDataSource
druid:
#连接池初始化连接
initial-size: 20
#最小空闲数
min-idle: 20
#最大连接数
max-active: 100
#最大等待时间
max-wait: 60000
#解密,放到druid下面,别处解密不到
connectionProperties: config.decrypt=true;config.decrypt.key=${publicKey}
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: admin
login-password: 123456
#慢sql
filter:
stat:
enabled: true
slow-sql-millis: 2000
log-slow-sql: true
#防火墙:drop表危险操作拦截
wall:
enabled: true
#开启后才会解密串
config:
enabled: true
#公钥
publicKey: 公钥串