原文:http://www.open-open.com/code/view/1453520072183
spring框架在一些對安全性要求較高的生產環境下,配置文件不允許出現明文用戶名密碼配置,如數據庫配置等。本文主要用於解決明文用戶名密碼加密。
通過繼承spring配置類並重寫處理方法實現密文解密
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
private String[] encryptPropNames = {"username", "password"};
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory,
Properties props) throws BeansException {
try {
for (int i = 0;i<encryptPropNames.length;i++){
String value = props.getProperty(encryptPropNames[i]);
if (value != null) {
props.setProperty(encryptPropNames[i],new String(DES.decrypt(new BASE64Decoder().decodeBuffer(value), "解密秘鑰")));
}
}
super.processProperties(beanFactory, props);
} catch (Exception e) {
e.printStackTrace();
throw new BeanInitializationException(e.getMessage());
}
}
}
配置applicationContext.xml文件,並在jdbc.properties中設置密文(根據解密秘鑰生成)
<!-- class填寫剛才那段代碼的類路徑-->
<bean id="propertyConfigurer" class="com.**.EncryptPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
