Spring中如何使用加密外部属性文件

最近看到网上有关Struts2远程访问安全的漏洞问题,不禁想到,如果项目中配置的敏感信息被黑客拿到就不好了,所以对于如配置jdbc.properties的文件里面的数据库用户名这类信息再用明文就不太安全了!虽然web应用系统的客户端用户看不到服务端的配置文件,但允许登陆到服务器的人还是很容易看到的。对于一些安全性要求较高的系统,最好采用加密!
信息的加密可分为对称和非对称两种方式,前者表示加密后的信息可以解密成原值,而后者则不能根据加密后的信息还原。MD5属于非对称加密,而DES属于对称加密,我们将使用DES对属性值进行加密;在读取到属性值时,再用DES进行解密。
下面是加密工具类
package com.demo.utils;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESUtils {

	private static Key key;
	private static String KEY_STR = "key";
	static {
		try{
			KeyGenerator generator = KeyGenerator.getInstance("DES");
			generator.init(new SecureRandom(KEY_STR.getBytes()));
			key = generator.generateKey();
			generator = null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 对字符串进行DES加密
	 * @param str
	 * @return 返回BASE64编码的加密字符串
	 */
	public static String getEncryptString(String str) {
		BASE64Encoder base64en = new BASE64Encoder();
		try {
			byte[] strBytes = str.getBytes("UTF8");
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] encryptStrBytes = cipher.doFinal(strBytes);
			return base64en.encode(encryptStrBytes);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 对BASE64编码的加密字符串进行解密
	 * @param str
	 * @return 解密后的字符串
	 */
	public static String getDecryptString(String str){
		BASE64Decoder base64De = new BASE64Decoder();
		try {
			byte[] strBytes = base64De.decodeBuffer(str);
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] decryptStrBytes = cipher.doFinal(strBytes);
			return new String(decryptStrBytes, "UTF8");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	
	public static void main(String[] args) {
		
		String str = "abcd";
		System.out.println(DESUtils.getEncryptString(str));
		String enStr = "BhykG14EE7o=";
		System.out.println(DESUtils.getDecryptString(enStr));
	}
	
}



在Spring中利用PropertyPlaceholderConfigurer进行解密,PropertyPlaceholderConfigurer本身不支持解密,通过扩展,覆盖String convertProperty(String propertyName, String ropertyValue)方法,对用户名和密码的属性时行解密
public class DemoPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigrer {
	protected String converProperty(String propertyName, String propertyValue) {
		if() { //属性是用户名或密码
			String decryptValue = DESUtils.getDecryptString(propertyValue);
			return decryptValue;
		} else {
			return propertyValue;
		}
	}
}



将其配置到Spring配置文件里,如:
<bean class="com.demo.DemoPropertyPlaceholderConfigurer" p:location="classpath:jdbc.properties" p:fileEncoding="utf-8" />



ps; BASE64Encoder 加密找不到jar包解决办法请参考 http://yzhw.iteye.com/blog/1700778

猜你喜欢

转载自yzhw.iteye.com/blog/1701254