需求
最近客户提了个需求,需要将配置文件中数据库用户名密码、ftp用户名密码、redis密码等敏感数据加密,遵循客户至上的原则,我们就干了
计划
计划或者说是改造计划,遵循的原则是不改动或者说尽可能少的改动代码是一个基本的原则。
项目采用springboot的架构,按理说直接@Value引入配置解密或者是添加配置类@EnableAutoConfiguration,在setter方法中设置即可(getter也行),事与愿违,项目的相关bean是引入了xml文件进行初始化的,这个想想还是可以实现的,只需要在读取配置文件的入口直接将密文解密即可,这么想来还是很简单的。
实现方案
springboot提供了个bean进行加载配置文件,直接重写org.springframework.beans.factory.config.PropertyPlaceholderConfigurer中的方法即可
代码实现
项目采用DES进行的加解密,在配置文件中在密文前面添加@DES前缀标识这个配置属性值是需要解密的
/**
* 读取配置文件时将配置的相关属性值解密
* 避免代码耦合,在这直接嵌入即可
*/
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
Logger logger = LoggerFactory.getLogger(EncryptPropertyPlaceholderConfigurer.class);
@Override
protected String convertProperty(String propertyName, String propertyValue) {
if(StringUtils.isEmpty(propertyValue)||StringUtils.isBlank(propertyValue)) {
return propertyValue;
}
// 值以DES@开头的均为DES加密,需要解密
if(propertyValue.startsWith("DES@")) {
logger.warn("解密配置文件密文{} = {} " ,propertyName,propertyValue);
return DESPlusHolder.decrypt(propertyValue.substring(4));
}
return super.convertProperty(propertyName, propertyValue);
}
}
改造xml配置文件中的propertyConfigurer bean的class实现类为上面我们自己重新的全类路径即可
<bean id="propertyConfigurer" class="com.xxx.xxx.xxx.common.EncryptPropertyPlaceholderConfigurer">
<property name="fileEncoding" value="utf-8" />
<property name="locations">
<list>
<value>classpath*:application.properties</value>
<value>classpath*:xx-xx-xxxx.properties</value>
<value>classpath*:applicationcontext-xxx-xxx-*.properties</value>
</list>
</property>
</bean>
完美解决,搞完后感觉还是很简单的,但还是很开心,需要的同学直接copy可用