方法一:使用数据库连接池 Druid中的非对称加密算法
1、引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
2、配置文件中配置
spring:
datasource:
driver-class-name: org.postgresql.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:postgresql://192.168.40.188:5432/hubt?characterEncoding=utf8&ssl=false
username: postgres
password: V6TSu+mFt/0B/cCv/sAcIkfLmXYE/CXAZIcjPRSClNCOwWhWn+AkSTIxhGK+38vnUqoAts3t/3NMNGgJNG9cUw==
publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIU6aAUEXOcfbdu7/ylAug4sk+YN5OgLV9n5pjNzcS//lU3wQ83lwBEycbeew/Ibl/EG0aUeC8kLYjlC+RCPjmcCAwEAAQ==
druid:
filter:
config:
enabled: true
connection-properties: config.decrypt=true;config.decrypt.key=${
spring.datasource.publicKey}
filters: stat,wall
获取配置中的公钥和加密后数据
public static void main(String[] args) throws Exception {
//密码明文
String password = "Jiao77473653637389838";
System.out.println("明文密码: " + password);
String[] keyPair = ConfigTools.genKeyPair(512);
//私钥
String privateKey = keyPair[0];
//公钥
String publicKey = keyPair[1];
//用私钥加密后的密文
password = ConfigTools.encrypt(privateKey, password);
System.out.println("privateKey:" + privateKey);
System.out.println("publicKey:" + publicKey);
System.out.println("password:" + password);
String decryptPassword = ConfigTools.decrypt(publicKey, password);
System.out.println("解密后:" + decryptPassword);
}
方法二
1、添加依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
2、创建工具类
public class JasyptUtil {
public static void main(String[] args) {
// 加密
String encPwd1 = encyptPwd("+oE67TSfU/j7+Mr4oKPLYg==", "postgres");
// 加密
String encPwd2 = encyptPwd("+oE67TSfU/j7+Mr4oKPLYg==", "998799797");
System.out.println(encPwd1);
System.out.println(encPwd2);
}
/**
* 加密方法
* @param password jasypt所需要的加密密码配置
* @param value 需要加密的密码
*/
public static String encyptPwd(String password, 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.encrypt(value);
return result;
}
3、配置文件陪加密后数据
jasypt:
encryptor:
password: +oE67TSfU/j7+Mr4oKPLYg==
# 指定加密方式
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
spring:
datasource:
driver-class-name: org.postgresql.Driver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:postgresql://192.168.40.199:5432/hubt?characterEncoding=utf8&ssl=false
username: ENC(RcclNxalLXIqBAIVgYN+hfLhvEw5BVGw)
password: ENC(YJ0R/uj65RkxR/i39KZP4yxePtQRTnDk)
以上数据库加密的ENC中的字符串为工具类加密后的数据