加密配置文件中的配置项

Posted binary-tree

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了加密配置文件中的配置项相关的知识,希望对你有一定的参考价值。

背景:
在配置文件中有些配置如:数据库密码等,为了安全起见需要进行加密,不过在其他程序读取这些配置项的时候需要得到真实的值。
解决方案:
继承Spring的PropertyPlaceholderConfigurer类重写convertProperty方法

import com.util.StringUtil;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.*;

public class MyPropertyPlaceHolder extends PropertyPlaceholderConfigurer 
    //需要加密的配置项名称
    private static Set<String> encryptPropList;
    public Map<String, String> map = new HashMap<String, String>();

    /**
     * 获取配置文件
     * @param props
     */
    @Override
    protected void convertProperties(Properties props) 
        System.out.println("convertProperties执行。。。");
        Set<String> set = props.stringPropertyNames();
        for(String item : set) 
            map.put(item, props.getProperty(item));
        
        super.convertProperties(props);
    

    /**
     * 重新设置配置项的值
     * @param propertyName
     * @param propertyValue
     * @return
     */
    @Override
    protected String convertProperty(String propertyName, String propertyValue) 
        if(encryptPropList.contains(propertyName)) 
            //将解密后的配置项放入spring的配置类中
            return StringUtil.decodeByBase64(propertyValue);
        
        return super.convertProperty(propertyName, propertyValue);
    

    public String getValue(String key) 
        if(encryptPropList.contains(key)) 
            return StringUtil.decodeByBase64(map.get(key));
        
        return map.get(key);
    

    public Set<String> getEncryptPropList() 
        return encryptPropList;
    

    public void setEncryptPropList(Set<String> encryptPropList) 
        this.encryptPropList = encryptPropList;
    

Spring配置:

<bean id="propertyConfigurer" class="com.entity.MyPropertyPlaceHolder">
    <property name="locations">
        <list>
            <!-- 这里支持多种寻址方式:classpath和file -->
            <value>classpath:com/entity/app.properties</value>
            <!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->
            <!--<value>file:/opt/demo/config/demo-mq.properties</value>-->
            <!--<value>file:/opt/demo/config/demo-remote.properties</value>-->
        </list>
    </property>
    <property name="encryptPropList">
        <set>
            <value>aliasName</value>
            <value>test</value>
        </set>
    </property>
</bean>

这样,在Spring中获取配置项时就是解密后的配置项了。当然需要先对配置项加密,然后注入到encryptPropList里。

以上是关于加密配置文件中的配置项的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot配置文件中的数据加密

winform程序如何加密配置文件

linux下c语言简单实现获取配置文件中的配置项

linux下c语言简单实现获取配置文件中的配置项

方向/配置更改后如何维护 ListView 片段状态?

易语言加密数据之后无法解密数据的问题