项目框架:spring
我们在开发应用时,需要连接数据库,一般把数据库信息放在一个属性配置文件中,比如jdbc.properties,具体的内容
jdbc.properties配置文件
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=root
jdbc.password=123456
里面用明文的方式存储着数据库的敏感信息用户名username和密码password,这是不好的行为,容易产生安全问题。那我们如何实现加密存储呢?
1、首先需要找一个对称加密工具进行加密解密:加密工具类
2、把加密后的数据放入到jdbc.properties配置文件中
jbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=73A949DD29845907
jdbc.password=F73556ABB1FB8849D72960B9CC30FF51d
3、自定义PropertyPlaceholderConfigurer类,在读取properties配置文件的时候进行解密
// 配置参数处理
public class DBPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private String[] encryptedProperties; // 需要解密的属key
private Properties properties; // 配置文件
public void setEncryptedProperties(String[] encryptedProperties) {
this.encryptedProperties = encryptedProperties;
}
@Override
protected void convertProperties(Properties properties) {
if(encryptedProperties != null) {
// 遍历需要解密的key
for(int i=0; i < encryptedProperties.length; i++) {
String key = encryptedProperties[i];
if(properties.containsKey(key)) {
String value = properties.getProperty(key);
// 解密
value = EncryptionUtil.decrypt(value);
// 重新赋值
properties.setProperty(key, value);
}
}
}
this.properties = properties;
super.convertProperties(properties);
}
public String getProperty(String key) {
return this.properties.getProperty(key);
}
}
4、在spring-config.xml配置文件
<!-- 注册自定义PropertyPlaceholderConfigurer类,解密Properties文件 -->
<bean id="placeholderConfigurer"
class="com.gpdi.mdata.utils.DBPropertyPlaceholderConfigurer">
<property name="locations" value="classpath:jdbc.properties" />
<property name="encryptedProperties">
<array>
<value>jdbc.username</value>
<value>jdbc.password</value>
</array>
</property>
</bean>
<context:property-placeholder location="classpath:jdbc.properties" ignore-resource-not-found="true"/>
注意:先后顺序为先注册PropertyPlaceholderConfigurer类,再是配置文件
这里使用的:加密工具类
---------------------
原文:https://blog.youkuaiyun.com/qq_37776015/article/details/90904606