数据库配置文件jdbc.properties 实现用户名密码加密

本文介绍在Spring框架中如何安全地加密存储数据库配置信息,包括使用加密工具类对敏感信息进行加密,自定义PropertyPlaceholderConfigurer类实现在读取配置时自动解密,以及在spring-config.xml中正确配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目框架: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 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MichaelYZ111

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值