【转载】加密Spring加载的Properties文件

目标:要加密spring的jdbc配置文件的密码口令。
 
实现思路:重写加载器的方法,做到偷梁换柱,在真正使用配置之前完成解密。

1.扩展

package com.rail.comm;

import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**  
 *   
 * 项目名称:rwoa  
 * 类名称:PropertyPlaceholderConfigurerExt  
 * 类描述:   对数据库用户名密码加密
 * 创建人:赵井桂  
 * 创建时间:2012-5-17 上午10:45:27  
 * 修改人:赵井桂 
 * 修改时间:2012-5-17 上午10:45:27  
 * 修改备注:  
 * @version   
 *   
 */
public class PropertyPlaceholderConfigurerExt extends PropertyPlaceholderConfigurer{
  @Override
  protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
                     throws BeansException {
       String username=props.getProperty("datasource.username");
             String password = props.getProperty("datasource.password");
            
             //解密jdbc.password属性值,并重新设置
          props.setProperty("datasource.username",Util.decrypt(username));
          props.setProperty("datasource.password",Util.decrypt(password));
             super.processProperties(beanFactory, props);
     }
}

2.Spring配置文件修改

//无加密

<!-- <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">-->

//加密后的
 <bean id="placeholderConfig" class="com.rail.comm.PropertyPlaceholderConfigurerExt">
  <property name="location">
   <value>classpath:init.properties</value>
  </property>
 </bean>

3.init.properties 文件修改

datasource.type=mysql
datasource.driverClassName=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://192.168.1.46:3306/rwoadb?useUnicode=true&characterEncoding=utf-8
datasource.username=2CCEE362A852387BD51C63E4780F2588
datasource.password=984027EDC2227C8EAF5D9733178C6418

4.加密算法实现,这里就不在赘述。

原文地址:https://www.cnblogs.com/huapox/p/3509632.html