Spring对properties文件的安全项进行加密
最近在对公司的www官网项目进行安全整改,其中有一项就是对配置文件中的安全信息进行加密处理,不得明文展示,比如数据库的连接串,用户名,密码等。
Spring在对properties文件进行处理得时候有一个类叫做PropertyPlaceholderConfigurer
,这个类可以指定加载的properties文件。
比如加载一个jdbc.properties
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username=test
jdbc.password=test
然后在XML中做如下配置:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigure">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
这样你就可以在XML文件中使用这些properties了:
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close" abstract="true">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}">
<property name="password" value="${jdbc.password}">
</bean>
可以看到数据库的连接串,用户名和密码都是明文存储的,泄露后可以直接登录数据库,风险很大,所以需要将这些信息加密。
可以通过继承PropertyPlaceholderConfigurer
,实现自己的获取属性值的方法:
public class NyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
// 需要解密的字段
private List<String> securityPropertyNames;
public List<String> getSecurityPropertyNames() {
return securityPropertyNames;
}
public void setSecurityPropertyNames(List<String> securityPropertyNames) {
this.securityPropertyNames = securityPropertyNames;
}
@Override
protected String convertProperty(String propertyName, String propertyValue) {
if(this.securityPropertyNames.contains(propertyName)){
return this.getProperty(propertyValue);
}
return super.convertProperty(propertyName, propertyValue);
}
private String getProperty(String value){
// 对value进行解密
// 使用RAS算法等
return value;
}
}
然后使用的时候如下:
<bean class="com.chengjf.util.MyPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="securityPropertyNames">
<list>
<value>jdbc.url</value>
<value>jdbc.password</value>
<value>jdbc.username</value>
</list>
</property>
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>