考虑到数据库连接密码直接配置在xml中,项目流转出现密码泄露隐患,这里直接对密码进行AES加密
<!-- 配置 读取properties文件 jdbc.properties -->
<bean class="com.yehuishou.util.ConvertPwdPropertyConfigurer">
<property name="location" value="classpath:jdbc.properties" />
<property name="fileEncoding" value="utf-8" />
</bean>
配置bean指定数据库文件的位置, class属性为重新的方法所在是全类名. 下面的
public class ConvertPwdPropertyConfigurer extends PropertyPlaceholderConfigurer {
//"driverClassName", "url", "username", "password" 必须与配置文件内的名字一致
private String[] encryptPropNames = { "driverClassName", "url", "username", "password" };
@Override
protected String convertProperty(String propertyName, String propertyValue) {
// 如果在加密属性名单中发现该属性
if (isEncryptProp(propertyName)) {
String decryptValue;
try {
decryptValue = AES.Decrypt(propertyValue);
} catch (Exception e) {
return propertyValue;
}
return decryptValue;
} else {
return propertyValue;
}
}
private boolean isEncryptProp(String propertyName) {
for (String encryptName : encryptPropNames) {
if (encryptName.equals(propertyName)) {
return true;
}
}
return false;
}
}
数组encryptPropNames里面的值就是你jdbc.properties 配置文件里面 的名称。
AES.Decrypt(propertyValue); 这个方法是调用AES的加密方法。
public class AES{
//AES加密的16位key
private static String sKey = "1234567887654321";
public static void main(String[] args) throws Exception {
System.out.println(AHEEHES.Encrypt(""));
System.out.println(AHEEHES.Decrypt(""));
}
// 加密
public static String Encrypt(String sSrc) throws Exception {
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
// 8866952612241802
byte[] raw = sKey.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// "算法/模式/补码方式"
IvParameterSpec iv = new IvParameterSpec("9876543223456789".getBytes());// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return org.apache.commons.codec.binary.Base64.encodeBase64String(encrypted);// 此处使用BAES64做转码功能,同时能起到2次加密的作用。
}
// 解密
public static String Decrypt(String sSrc) throws Exception {
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.print("Key长度不是16位");
return null;
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec("9876543223456789".getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
byte[] encrypted1 = org.apache.commons.codec.binary.Base64.decodeBase64(sSrc);// 先用bAES64解密
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
}
Key的长度必须是16,24,32位 , 这里用的是AES-128-CBC加密模式 , key需要16
使用AES加密需要的pom坐
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>