信息的加密可分为对称和非对称两种方式,前者表示加密后的信息可以解密成原值,而后者则不能根据加密后的信息还原。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