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来匹配配置文件中的密文是否正确。


经验分享 程序员 微信小程序 职场和发展