使用spring的PropertyPlaceholderConfigurer加密properties文件中的属性
2017-02-15 15:41
519 查看
一、背景
处于安全考虑需要对.properties中的数据库用户名与密码等敏感数据进行加密。项目中使用了Spring3框架统一加载属性文件,所以最好可以干扰这个加载过程来实现对.properties文件中的部分属性进行加密。属性文件中的属性最初始时敏感属性值可以为明文,程序第一次执行后自动加密明文为密文。
二、问题分析
扩展PropertyPlaceholderConfigurer最好的方式就是编写一个继承该类的子类。外部设置locations时,记录全部locations信息,为加密文件保留属性文件列表。重写setLocations与setLocation方法(在父类中locations私有)
寻找一个读取属性文件属性的环节,检测敏感属性加密情况。对有已有加密特征的敏感属性进行解密。重写convertProperty方法来实现。
属性文件第一次加载完毕后,立即对属性文件中的明文信息进行加密。重写postProcessBeanFactory方式来实现。
三、代码实现
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <!-- 加密 --> <property name="locations"> <list> <value>classpath:db.properties</value> </list> </property> <!-- 声明需要加密的属性 --> <property name="encryptedProps"> <set> <value>db.jdbc.username</value> <value>db.jdbc.password</value> <value>db.jdbc.url</value> </set> </property> </bean>
package com.sgfm.test; import com.sgfm.base.des.DESEncryptUtil; public class Test { private static final String SEC_KEY = "@^_^123aBcZ*"; // 主密钥 private static final String ENCRYPTED_PREFIX = "{";// 默认加密前缀 private static final String ENCRYPTED_SUFFIX = "}";// 默认加密后缀 public static void main(String[] args) throws Exception { DESEncryptUtil dec = new DESEncryptUtil(); String encryptStr = dec.encrypt("tcp://192.168.10.242:61616", SEC_KEY);// 加密 String decryptStr = dec.decrypt("1B7328C79D9D5BC37E0636947EFEECD6E1459B4260497E31000754134655A350", SEC_KEY);// 解密 System.out.println("加密内容:" + encryptStr); System.out.println("解密内容:" + decryptStr); } }原属性文件
db.jdbc.driver=com.mysql.jdbc.Driver db.jdbc.url=jdbc:mysql://localhost:3306/noah?useUnicode=true&characterEncoding=utf8 db.jdbc.username=noah db.jdbc.password=noah
加密后的文件
db.jdbc.driver=com.mysql.jdbc.Driver db.jdbc.url=Encrypted:{e5ShuhQjzDZrkqoVdaO6XNQrTqCPIWv8i_VR4zaK28BrmWS_ocagv3weYNdr0WwI} db.jdbc.username=Encrypted:{z5aneQi_h4mk4LEqhjZU-A} db.jdbc.password=Encrypted:{v09a0SrOGbw-_DxZKieu5w}
相关文章推荐
- 使用Spring替换properties文件定义属性的方法
- spring中获得属性文件键值对,在程序中使用
- Spring 使用外部属性文件(连接数据库)
- spring管理属性配置文件properties——使用PropertiesFactoryBean
- spring(9) Spring中使用外部属性文件
- Spring的配置文件中使用属性文件
- spring4学习:使用外部属性文件
- 记录:使用IDEA编辑Spring配置文件profile属性时产生的命名重复问题
- Spring中属性文件properties的读取与使用
- spring中使用外部属性文件(关于PropertyPlaceholderConfigurer)
- Spring IOC使用外部属性文件
- Spring---Bean使用外部属性文件
- spring-自动加载配置文件\使用属性文件注入
- spring ioc之使用外部属性文件
- spring与jpa整合 简化persistence.xml配置文件 使用属性文件 数据源dbcp访问数据库
- spring 使用外部属性文件
- Spring中属性文件properties的读取与使用
- Spring中使用Map、Set、List、数组、属性集合的注入方法配置文件
- 使用Spring实现属性文件给常量赋值