项目的安全需要 现在对配置文件中 敏感的明文信息进行加密
(当前示例架构 Spring MVC )
例如:配置文件中经常会存放 数据库的链接信息 帐号密码
加解密原理:Spring 的在读取配置文件时 使用的是org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 类
因此我们要自定义这个加载类,在读取配置文件的方法里对信息进行加解密操作
第一步:新建 配置文件读取配置类
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
public class MyPropertyConfigurer extends PropertyPlaceholderConfigurer {
@Override
protected String convertProperty(String propertyName, String propertyValue) {
//propertyName:配置文件key propertyValue:对应的值
//在此可做解密处理,可根据不同的propertyName 做对应操作
if("password".equals(propertyName)){
//配置文件中密码用Aes 进行加密的,此处进行解密
return Aes256Util.aesCbcDecrypt(propertyValue);
}
//未做加密的调用convertPropertyValue 方法 返回原本值
return convertPropertyValue(propertyValue);
}
}
这边要注意一点,大家用的spring 版本不一致 继承PropertyPlaceholderConfigurer 后 不一定可以重写convertProperty这个方法 需要根据源码随机应变,上方的spring 的版本是3.0以上的
我还遇到低版本 是没有convertProperty(String propertyName, String propertyValue) 这个方法的
因此通过源码 我进行了改造
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
public class MyPropertyConfigurer extends PropertyPlaceholderConfigurer {
@Override
protected void convertProperties(Properties props) {
Enumeration<?> propertyNames = props.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String) propertyNames.nextElement();
String propertyValue = props.getProperty(propertyName);
//低版本 直接在这调用convertPropertyValue()方法,现在在这进行优化,新增convertProperty方法
String convertedValue = convertProperty(propertyName, propertyValue);
if (!ObjectUtils.nullSafeEquals(propertyValue, convertedValue)) {
props.setProperty(propertyName, convertedValue);
}
}
}
/**
*版本Spring 没有该方法
*此处进行新增
*
*/
protected String convertProperty(String propertyName, String propertyValue) {
//propertyName:配置文件key propertyValue:对应的值
//在此可做解密处理,可根据不同的propertyName 做对应操作
if("password".equal(propertyName)){
//配置文件中密码用Aes 进行加密的,此处进行解密
return Aes256Util.aesCbcDecrypt(propertyValue);
}
//未做加密的调用convertPropertyValue 方法 返回原本值
return convertPropertyValue(propertyValue);
}
@Override
protected String convertPropertyValue(String originalValue){
return originalValue;
}
}
第二步:applicationContext.xml(本项目是在此xml 文件中 对配置文件读取做出配置的,有些因为架构的原因 可能在其他配置文件中)
<bean id="placeholderConfig"
//将org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 替换成 自定义的类
class="com.my.config.MyPropertyConfigurer">
<property name="location">
<value>classpath:jdbc.properties</value>
</property>
</bean>
第三步:对配置文件jdbc.properties 中的文件 加密
我用的是Aes 进行加密 先将明文 加密成密文
然后将密文的字符串放入jdbc.properties 中的文件 对应的值即可
心得:这类配置 看起来很难很复杂 其实静下心来 ,抽丝剥茧,总能找到它的关键之处,在去看其他配置类的源码 ,其实也没那么困难了