1. 程式人生 > >spring xml讀取Properties檔案中的加密欄位

spring xml讀取Properties檔案中的加密欄位

spring的xml配置檔案,能夠方便地讀取properties檔案中的值。

讀取單個屬性檔案:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations" value="classpath:password.properties"/>
</bean>
讀取多個屬性檔案:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
		<list>
			<value>classpath:a1.properties</value>
			<value>classpath:a2.properties</value>
		</list>
	</property>
</bean>

不過spring自帶的PropertyPlaceholderConfigurer是將屬性檔案中的值原樣讀出。實際上一般的密碼等敏感資訊,專案中都會進行加密儲存。也就是說properties中儲存的是加密後的結果,這樣必需解密後才能使用。

我們可以繼承PropertyPlaceholderConfigurer來實現解密:

package net.aty.spring.ioc.password;

import java.util.List;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class EncryptPropertyPlaceholderConfigurer extends
		PropertyPlaceholderConfigurer {

	private List<String> encryptPropNames;

	@Override
	protected String convertProperty(String propertyName, String propertyValue) {

		if (encryptPropNames.contains(propertyName)) {
			return DESUtil.decrypt(propertyValue);
		}

		return super.convertProperty(propertyName, propertyValue);
	}

	public List<String> getEncryptPropNames() {
		return encryptPropNames;
	}

	public void setEncryptPropNames(List<String> encryptPropNames) {
		this.encryptPropNames = encryptPropNames;
	}
}
package net.aty.spring.ioc.password;

import java.io.UnsupportedEncodingException;

import org.springframework.util.Base64Utils;

public class DESUtil {

	public static String encrypt(String src) {
		try {
			return Base64Utils.encodeToString(src.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static String decrypt(String src) {
		try {
			return new String(Base64Utils.decodeFromString(src), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	
	public static void main(String[] args) {
		System.out.println(encrypt("aty"));
		System.out.println(encrypt("123456"));
	}
}

對應的properties檔案如下:
userName = aty
password = 123456

userName.after.encrypt=YXR5
password.after.encrypt=MTIzNDU2
spring配置檔案如下:
<bean class="net.aty.spring.ioc.password.EncryptPropertyPlaceholderConfigurer">
	<property name="encryptPropNames">
		<list>
			<value>userName.after.encrypt</value>
			<value>password.after.encrypt</value>
		</list>
	</property>
	<property name="locations">
		<list>
			<value>classpath:password.properties</value>
		</list>
	</property>
</bean>

<bean id="atyBean" class="net.aty.spring.ioc.password.ShowPasswordBean">
	<property name="name" value="${userName.after.encrypt}" />
	<property name="password" value="${password.after.encrypt}" />
</bean>


如此即可實現解密: