Druid数据库密码加密
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}为加密后的密码