网上的坑
springboot 使用 Druid 数据库加密链接方案,不建议采用网上的一篇文章《springboot 结合 Druid 加密数据库密码遇到的坑!》介绍的方式来进行加密链接实现。本文章下文分享 Druid 源码后就知道为什么不建议采用该方式的原因了。
加密准备
首先使用 CMD 生成数据库加密字符串,该命令会产生三个值 privateKey=公钥、publicKey=密码加密后的结果、password=密码加密串
java -cp druid-1.0.28.jar com.alibaba.druid.filter.config.ConfigTools pcds123123456
使用 Durid 的工具类 ConfigTools 验证加密字符串
@Test
public void db_decrypt_test() throws Exception {
String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJggkaRJ+bqLMF6pefubEDLViboxYKGTdGe+78DziIta8Nv8crOA83M0tFG8y8CqHcFYIbG89q9zcnNvL+E2/CECAwEAAQ==";
String password = "AgDRyKJ81Ku3o0HSyalDgCTtGsWcKz3fC0iM5pLur2QJnIF+fKWKFZ6c6e36M06tF2uCadvS/EodWxmRDWwvIA==";
System.out.println(ConfigTools.decrypt(publicKey, password));
}
实现方案
SpringBoot 集成 Druid 数据库链接加密的方式,推荐使用配置注入方式初始化 DataSource。方法如下:
一、增加配置注入 Bean
import java.sql.SQLException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class DbConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(DbConfig.class);
private String url;
private String driverClassName;
private String username;
private String password;
private Integer initialSize;
private Integer minIdle;
private Integer maxActive;
private Integer maxWait;
private Integer timeBetweenEvictionRunsMillis;
private Integer minEvictableIdleTimeMillis;
private String validationQuery;
private Boolean testWhileIdle;
private Boolean testOnBorrow;
private Boolean testOnReturn;
private Boolean poolPreparedStatements;
private Integer maxOpenPreparedStatements;
private Integer maxPoolPreparedStatementPerConnectionSize;
private String filters;
private String publicKey;
private String connectionProperties