接下来我的做法是将这些密码加密后用{{}}包围起来, properties中这样写
jdbc.driverClassName=com.ibm.db2.jcc.DB2Driver
jdbc.url=jdbc:db2://192.168.1.101:50000/XXXX
jdbc.username=db2inst1
jdbc.password={{9432E7976A6BBF9E}}
然后使用自定义的PlaceholderConfigurer.,在其中将其解密以便application能正常使用, applicationContext.xml配置如下:
<bean id="propertyPlaceholderConfigurer"
class="com.xxx.util.EncryptedPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:xxxx.properties</value>
</list>
</property>
</bean>
java代码如下:
/**
* Created by cyper on 1/21/15.
*/
public class EncryptedPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
public static final String PREFIX = "{{";
@Override
protected String convertPropertyValue(String originalValue) {
if (originalValue.startsWith(PREFIX)) {
logger.debug("Find encrypted value:" + originalValue);
String newValue = originalValue.substring(2, originalValue.length() - 2);
newValue = DES.decrypt(newValue);
return newValue;
}
return originalValue;
}
}
其中的DES类可以替换成任意的可逆加密算法类。
这样做能在一定程度上使你的应用程序更安全(简单的文件扫描或肉眼观察并不能直接得到密码,需要找到解密类进行解密)
参考:http://kayalvizhiameen.blogspot.in/2014/04/handling-obfuscated-property-values-in.html?view=classic, 比文中的简单.
写完后发现这里有一篇:http://my.oschina.net/noahxiao/blog/163719 不过感觉太长了,还是我的简单。 :D