SpringBoot使用Druid數據庫加密鏈接完整方案
阿新 • • 發佈:2019-01-02
生成 too ntp conn github cut 解密 hub 資料
網上的坑
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