c3p0,druid,springboot项目使用数据库配置文件加密访问

数据库加密访问

原理

将配置文件中的密码进行加密使其以密文方式存在,在初始化链接池时进行解密操做,达到成功建立链接池的目的。java

目前主要使用的链接池有如下几个:mysql

  • c3p0
  • druid
  • springboot框架的链接池

C3P0链接池

  1. jdbc.properties中密码由明文改为密文
  2. 在配置com.mchange.v2.c3p0.ComboPooledDataSource的地方 ,增长properties属性,编写一个PropertiesFactory类,实现password的解密操做便可。
  • 编写DatasourcePropertiesFactory类git

    public class DatasourcePropertiesFactory { 
    
        private static final String PASSWORD_PROPERTY = "password"; 
        public static Properties getProperties(String password) throws Exception { 
            Properties properties = new Properties(); 
            try { 
                /** 
                 * 这里对参数password进行解密获得解密后的密码
                 */ 
                String decodePassword = 解密(password) 
                properties.setProperty(PASSWORD_PROPERTY, decodePassword); 
            } catch (Exception e) { 
           		//处理异常
            } 
            return properties; 
        } 
    }
  • 修改spring.xml中数据源datasource的配置,为ComboPooledDataSource配置名为properties的属性,同时取消password的property配置项github

    <property name="properties"> 
                <bean class="com.xxx.datasource.CustomDatasourcePropertiesFactory" 
                    factory-method="getProperties"> 
                    <constructor-arg type="java.lang.String"> 
                        <value>${jdbc.password}</value> 
                    </constructor-arg> 
                </bean> 
    </property>

Druid链接池

  • druid链接池默认使用RSA加密链接,修改解密算法比较麻烦,建议直接使用druid提供的工具进行加解密算法

    1. cmd控制台使用如下命令获取公私钥、加密密文
    java -cp druid-1.0.31.jar com.alibaba.druid.filter.config.ConfigTools your_password
    1. 修改jdbc.properties中密码改为上面控制台中获取到的加密密码,注意不要复制成公私钥,若是有配置testOnReturn 和testOnBorrow 的必定要设置成true
    2. 修改spring.xml中com.alibaba.druid.pool.DruidDataSource 的配置,增长如下配置
    <!-- config.decrypt=true --> 
    <property name="filters" value="config" /> 
    <property name="connectionProperties" value="config.decrypt=true" />

    能够参考官网信息【官网】https://github.com/alibaba/druid/wiki/使用ConfigFilterspring

springboot框架

springboot引入jasypt进行加解密操做,默认加密算法是PBEWithMD5AndDES,一种结合PBE,MD5和DES的复合加密算法sql

  1. maven引入jasypt依赖
<dependency>
	<groupId>com.github.ulisesbocchio</groupId>
	<artifactId>jasypt-spring-boot-starter</artifactId>
	<version>2.1.0</version>
</dependency>
  1. 配置加密密钥
jasypt:
  encryptor:
    password: 123456这个密钥由运维提供
  1. 编写测试用例获取加密密码(也能够在控制台使用java命令获取)
@Autowired
    StringEncryptor stringEncryptor;

    @Test
    public void encryptPwd() {
        String result = stringEncryptor.encrypt("yourpassword");
        System.out.println(result); 
    }
  1. 修改配置文件application.yml中password项,用ENC()括起来
spring:
  datasource:
    url: jdbc:mysql://192.168.171.231:3306/eoc?characterEncoding=utf8&useUnicode=true
    username: test
    password: ENC(括号里面填上面获取到的加密密文)
相关文章
相关标签/搜索