常看到程序中数据配置文件(jdbc.properties或datasource.properties等)中配了一个密文密码
整个解析过程是这样的:
》项目启动的时候,解析配置文件(借用了spring):
<!-- 读取环境变量的东西--> <bean id="propertyConfigurer" class="com.tools.PropertyPlaceSpecialConfigurer"> <property name="locations"> <list> <value>file:${HLJJAVAENV}/hljinstservice/jdbc.properties</value> <value>file:${HLJJAVAENV}/hljinstservice/conf.properties</value> </list> </property> </bean>
这里是把文件位置配在了环境变量里,可根据自己的配置文件情况在value里写对应的值
》
package com.tools; import java.util.Properties; import company.tools.util.PassWordUtil; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; /** * */ public class PropertyPlaceSpecialConfigurer extends PropertyPlaceholderConfigurer { @Override protected String resolvePlaceholder(String placeholder, Properties props) { String value = props.getProperty(placeholder); //如果是密码,且长度为 if(placeholder.equals("jdbc.password")){ //超过32位我就认为是加密过的密码,我来解密下 try { value = PassWordUtil.getPasswordThreeDesDecTwo(value); } catch (Exception e) { } } return value; } }
这里自定义PropertyPlaceSpecialConfigurer 类,继承spring的PropertyPlaceholderConfigurer ,重写了resolvePlaceholder方法,看到这里就明白了密文是怎么解析的,PassWordUtil自定义的密码工具类,调取自己写的解密方法,将密文解密。