在实际项目中,经常需要对数据库连接池的相关配置加密,比如说数据库的密码,下面介绍两种加密和解密方法
一,重写数据库连接池
import org.apache.commons.codec.binary.Base64; import org.apache.commons.dbcp.BasicDataSource; import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger; /** * @author:lyy * @Date: 2016/2/6 12:16 * @version: * @Description: */ public class UnisConnection extends BasicDataSource { private String salt = "unis"; private String mix = "Th"; public UnisConnection() { super(); } @Override public void setPassword(String password){ try{ this.password = decodeUnisPassword(password); }catch(Exception e){ } } /** * Return the parent Logger of all the Loggers used by this data source. This * should be the Logger farthest from the root Logger that is * still an ancestor of all of the Loggers used by this data source. Configuring * this Logger will affect all of the log messages generated by the data source. * In the worst case, this may be the root Logger. * * @return the parent Logger for this data source * @throws SQLFeatureNotSupportedException if the data source does not use * {@code java.util.logging} * @since 1.7 */ @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } /** * @author: lyy * @Time: 2016/2/6 13:58 * @Descrption: 根据密码串,反编码出真正的数据库密码 * @param encodeStr 密码串 * @return 原始密码串 * @throws */ private String decodeUnisPassword(String encodeStr){ String temp = new String(Base64.decodeBase64(encodeStr)); temp = temp.substring(mix.length()); temp = new String(Base64.decodeBase64(temp)); return temp.substring(salt.length()); } }
然后在配置连接池时,进行如下配置
<bean id="dataSource" class="com.unisits.zngkpt.data.userprivrmandata.bojo.UnisConnection" destroy-method="close">
<property name="driverClassName" value="${driverClasss}"/>
<property name="url" value="${jdbcUrl}"/>
<property name="username" value="${loginusername}"/>
<property name="password" value="${password}"/>
<!-- 初始化连接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
具体的属性为:
loginusername=sa
password=VGhkVzVwYzNSb2RXNXBjdz09
二,重写PropertyPlaceholderConfiger类
详见精通spring4.0 --< 6.3.2