1. 程式人生 > >Spring 中使用jasypt對配置檔案(.properties)中密碼加密

Spring 中使用jasypt對配置檔案(.properties)中密碼加密

spring配置中經常使用placeholder來載入一個應用配置檔案(.properties),但是其中的各種密碼以明文顯示出來總該是不好。

不過可以利用jasypt這個框架來擴充套件這個加密功能,需要用到jasypt中的icu4j-version.jar、jasypt-version-lite.jar、jasypt-version.jar和jasypt-spring31-version.jar

首先,註釋掉原有的placeholder載入方式

<!--<context:property-placeholder location="/WEB-INF/config.properties"/> -->
然後使用jasypt為spring相應版本實現的placeholder
<!-- decrypt password in config.properties -->
	<bean id="environmentVariablesConfiguration"
		class="org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig">
		<property name="algorithm" value="PBEWithMD5AndDES" />
		<property name="password" value="root" />
	</bean>
	<bean id="configurationEncryptor" class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">
		<property name="config" ref="environmentVariablesConfiguration" />
	</bean>
	<bean id="propertyConfigurer"
		class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer">
		<constructor-arg ref="configurationEncryptor" />
		<property name="locations">
			<list>
				<value>/WEB-INF/config.properties</value>
			</list>
		</property>
		<property name="fileEncoding" value="utf-8" />
	</bean> 
最後,修改.properties配置中的明文密碼為密文,這個需要自己寫一個main方法
public static void main(String[] args) {
		//PBEWithMD5AndDES
		BasicTextEncryptor encryptor = new BasicTextEncryptor();
		encryptor.setPassword("root");
		String encrypted = encryptor.encrypt("xxxx");
		System.out.println(encrypted);
	}
然後將輸出的密文替換原來的密碼
jdbc.password=ENC(jHv0WdiTLJFmOO08RQtUpg==)

這樣的密文雖然還是很容易被decode出來,但終究不是明文顯示。

個人認為最好的辦法可能是 自己去實現一個spring的 place holder,利用md5來匹配配置檔案中的密文是否正確。