Spring加载加密的配置文件


一、继承并实现自己的属性文件配置器类

/**
 * 带加密的Spring属性配置文件扩展类
 * 加密方式:AES
 * @author simon
 *
 */
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    //指定需要加密的属性
    private String[] propertyNames = {"db.password"};

    /**
     * 解密指定propertyName的属性值
     * @param propertyName
     * @param propertyValue
     * @return
     */
    @Override
    protected String convertProperty(String propertyName, String propertyValue) {
        //过滤出需要解密的属性
        for (String p : propertyNames) {
            if (p.equalsIgnoreCase(propertyName)) {
                try {
                   //返回AES解密后的字符串
                   return new String(SymmetricCryptoUtil.decryptAESWithDefaultKey(EncodeUtil.decodeBase64(propertyValue)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return super.convertProperty(propertyName, propertyValue);
    }

}

二、Spring中配置以自定义的属性文件配置器类来加载加密后的配置文件

<!-- 加载加密后的配置文件 -->
<bean class="com.bounter.mybatis.extension.EncryptPropertyPlaceholderConfigurer">
  <property name="locations">
    <list>
      <value>classpath:db.properties</value>
    </list>
  </property>
</bean>

三、将配置文件中的特殊属性用相同的算法和密钥加密

db.driver=
db.url=
db.username=root
#AES encrypt,Base64 encode
db.password=jFYmt2f57RHhzItYDhWiSA==

github源码地址:https://github.com/13babybear/bounter-mybatis

原文地址:https://www.cnblogs.com/gdufs/p/7148022.html