出于对安全的考虑,需要对项目里面的.properties文件中的数据进行加密,确保项目被黑客攻击后任然无法得到敏感数据。Spring3框架提供了统一加载属性文件的方法PropertyPlaceholderConfigurer,所以最好可以在这个加载之前实现对.properties文件中的属性进行加密/解密处理。
配置文件中的属性最初始时敏感属性值可以在上线之前加密明文得到密文,程序加载后读取到的是密文,需要在PropertyPlaceholderConfigurer读取之前解密。
编写一个继承类,继承PropertyPlaceholderConfigurer,对密文的属性进行解密。DESUtil.java工具类可以参考https://mp.csdn.net/mdeditor/79815134
转载请注明:https://blog.csdn.net/qfashly/article/details/79815473
public class EncryptProperties extends PropertyPlaceholderConfigurer {
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
DESUtil des = new DESUtil(DESUtil.KEY_ARR[0]);
Enumeration<Object> eKeys = props.keys();
Object ooKey = null;
String pKey = null;
String pValue = null;
while (eKeys.hasMoreElements()) {
ooKey = eKeys.nextElement();
if (ooKey == null) {
continue;
}
pKey = String.valueOf(ooKey);
pValue = props.getProperty(pKey);
if (pValue == null) {
continue;
}
pValue = pValue.trim();
//对明文加密
if (pValue.startsWith("{DES}")) { //如果是以 {DES} 开头的, 则认为是加密数据
try {
props.setProperty(pKey, des.decryptStr(pValue.substring(5, pValue.length())));
} catch (Exception e) {
e.printStackTrace();
}
}
//对密文解密
/*if(!pValue.startsWith("{DES}")){ //如果是以 {DES} 开头的, 则认为是加密数据
try {
props.setProperty(pKey, des.encryptStr(pValue));
} catch (Exception e) {
e.printStackTrace();
}
}*/
}
super.processProperties(beanFactoryToProcess, props);
}
}
在applicationContext.xml加上
<bean id="propertyConfig" class="com.fw.core.server.ds.config.EncryptProperties">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:system.properties</value>
</list>
</property>
</bean>