spring读取加密配置信息

描述&背景
Spring框架配置数据库等连接等属性时,都是交由 PopertyPlaceholderConfigurer进行读取.properties文件的,但如果项目不允许在配置文件中明文保存密码等重要的连接信息,此时,唯有继承PopertyPlaceholderConfigurer,并重写convertProperty(String propertyName, String propertyValue)方法,该方法是java中少有的传参承载设计模式,在这里,我们可以拿到我们需要进行解密的密文再传给spring组件去连接数据库,避免了明文保存。所以我们可以将加密后的信息保存到.Properties文件中,在读取前解密,就可以实现不明文保存信息需求。这里我将用AES来加密重要信息。
步骤
1. 导加密工具文件
将AES加密文件放到项目工具类的位置,如有其它加密和解密工具,可不用我这个AES加密。
2. 继承PropertyPlaceholderConfigurer

package com.openeap.common.web;



import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.openeap.common.utils.aes.AESEncryptor;

public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
    private String[] encryptPropNames = {"jdbc.username", "jdbc.password"};  
    private String code = "gzxcxxxtgcyxgs01";
    @Override  
    protected String convertProperty(String propertyName, String propertyValue)  
    {  
        //如果在加密属性名单中发现该属性  
        if (isEncryptProp(propertyName))  
        {  
            String decryptValue="";
            try {
                decryptValue = AESEncryptor.decrypt(code, propertyValue);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         System.out.println(decryptValue);
return decryptValue==""?propertyValue:decryptValue; }else { return propertyValue; } } private boolean isEncryptProp(String propertyName) { for (String encryptName : encryptPropNames) { if (encryptName.equals(propertyName)) { return true; } } return false; } }

AES加密,还需要一个code,这里需要一个是16位或者16位配数的密钥当spring读取到带有encryptPropNames包含的字段时,会执行convertProperty方法进行解密
注:.propertites文件中保存的格式为
jdbc.username=admin
jdbc.password=123456

3. Spring配置文件配置
在spring加载属性配置文件时,用

<bean class="com.openeap.common.web.EncryptPropertyPlaceholderConfigurer"  >
         <property name="ignoreUnresolvablePlaceholders" value="true"></property>
        <property name="locations">    
           <list>    
               <value>classpath*:/application.properties</value>    
           </list>    
       </property>  
    </bean>

替换原来的

<context:property-placeholder ignore-unresolvable="true" location="classpath*:/application.properties" />

4. 计算加密后的信息
AES加密方法中encrypt(String seek, String cleartext),例如原始值是aaa,密钥是1234567887654321,得到的密码是N!Kk8dwLm0z7hlGkq2dbdQ==

最后将密文信息回填到.properties文件中。

jdbc.username=N!Kk8dwLm0z7hlGkq2dbdQ==

至此,spring不在配置信息里保存重要的明文信息了。

如有错误,恳请指正,不胜感激!

===============我是分割线==============

AES加密文件下载地址

http://pan.baidu.com/s/1jH6bM3W

如失效请邮件通知我,cngdsch@163.com

原文地址:https://www.cnblogs.com/maixiaodou/p/6126777.html