1 Druid官方提供的數據庫密碼加密
1.1執行命令加密數據庫密碼
在命令行中執行如下命令:
java -cp druid-1.0.16.jar com.alibaba.druid.filter.config.ConfigTools you_password
1.2 配置數據源,提示Druid數據源需要對數據庫密碼進行解密。
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
- init-method="init" destroy-method="close">
- <property name="url" value="jdbc:derby:memory:spring-test;create=true" />
- <property name="username" value="sa" />
- <property name="password" value="${password}" />
- <property name="filters" value="config" />
- <property name="connectionProperties" value="config.decrypt=true;config.decrypt.key=${publickey}" />
- </bean>
1.3 配置參數,讓ConfigFilter解密密碼
有三種方式配置:
1) 可以在配置文件my.properties中指定config.decrypt=true
2) 也可以在DruidDataSource的ConnectionProperties中指定config.decrypt=true
3) 也可以在jvm啟動參數中指定-Ddruid.config.decrypt=true
2. 自定義數據庫密碼加密方法
1. 實現DBPasswordCallback
- package com.netposa.security;
- import com.alibaba.druid.util.DruidPasswordCallback;
- import org.apache.commons.lang3.StringUtils;
- import java.util.Properties;
- /**
- * Created by Administrator on 2016/11/7.
- */
- public class DBPasswordCallback extends DruidPasswordCallback {
- @Override
- public void setProperties(Properties properties) {
- super.setProperties(properties);
- String pwd = properties.getProperty("password");
- if (StringUtils.isNoneBlank(pwd)) {
- try {
- //這里的password是將jdbc.properties配置得到的密碼進行解密之后的值
- //所以這里的代碼是將密碼進行解密
- //TODO 將pwd進行解密;
- String password = decrypt(pwd);
- setPassword(password.toCharArray());
- } catch (Exception e) {
- setPassword(pwd.toCharArray());
- }
- }
- }
- private String decrypt(String src)
- {
- //解密
- }
- }
2、配置Druid的數據庫連接池
- <bean id="dbPasswordCallback" class="com.netposa.security.DBPasswordCallback" lazy-init="true"/>
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
- <property name="driverClassName" value="${datasource.jdbc.driver}"/>
- <property name="url" value="${datasource.jdbc.url}"/>
- <property name="username" value="${datasource.jdbc.username}"/>
- <property name="password" value="${datasource.jdbc.password}"/>
- <property name="passwordCallback" ref="dbPasswordCallback"/>
- <property name="connectionProperties" value="password=${datasource.jdbc.password}" />
- <property name="passwordCallback" ref="dbPasswordCallback"/>
- <property name="connectionProperties" value="password=${datasource.jdbc.password}" />
- ${datasource.jdbc.password}為加密后的密碼
