Java開發小技巧(四):配置文件敏感信息處理
阿新 • • 發佈:2017-12-22
加載 gem 加密解密 -i false valid ges enc factory
前言
不知道在上一篇文章中你有沒有發現,jdbc.properties
中的數據庫密碼配置是這樣寫的:
jdbc.password=5EF28C5A9A0CE86C2D231A526ED5B388
其實這不是真正的密碼,而是經過AES加密的。
AES的Java實現
AES(高級加密標準)是美國聯邦政府采用的一種區塊加密標準,其替代原先的
DES加密算法,成為對稱密鑰加密中最流行的算法之一。
AES加密解密的實現就不具體介紹了,這裏直接給出源碼:
package com.demo.project.monitor.util;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class AESEncryption {
private String password = "Password";
public AESEncryption(){
}
public AESEncryption (String password){
this.password = password;
}
/**
* 加密
* @param content 加密內容
* @return
*/
public String encrypt(String content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes ()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return parseByte2HexStr(result); // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**解密
* @param content 解密內容
* @return
*/
public String decrypt(String content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(parseHexStr2Byte(content));
return new String(result); // 解密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 將二進制轉換成16進制
* @param buf
* @return
*/
private String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = ‘0‘ + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 將16進制轉換為二進制
* @param hexStr
* @return
*/
private byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
解密配置文件
既然配置文件部分內容已經進行了加密處理,那我們在填充上下文的占位符時就要對其進行解密,獲得真正的密碼,還記得之前我們在加載配置文件的時候使用的類PropertyPlaceholderConfigurer
嗎?我們可以通過對它的resolvePlaceholder
方法進行重寫來實現。
實現過程
首先創建一個繼承自PropertyPlaceholderConfigurer
的類EncryptPropertyPlaceholderConfigurer
,然後重寫它的方法:
package com.demo.project.monitor.util;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.Properties;
/**
* 解密配置文件敏感內容
*/
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
@Override
protected String resolvePlaceholder(String placeholder, Properties props) {
String result = props.getProperty(placeholder);
if(placeholder.endsWith("jdbc.password")){
AESEncryption aes = new AESEncryption();
String decrypt = aes.decrypt(result);
result = decrypt == null ? result : decrypt;
}
return result;
}
}
接著在spring上下文中將原來的beanorg.springframework.beans.factory.config.PropertyPlaceholderConfigurer
修改為我們創建的類即可:
<bean class="com.demo.project.monitor.util.EncryptPropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
<property name="ignoreResourceNotFound" value="false"/>
</bean>
這樣spring在填充占位符的時候就會進行判斷,對加密後的敏感信息進行解密處理,得到真實的內容。
文章項目源碼已發布到Github:https://github.com/ZKHDEV/MultDependPjo
本文為作者kMacro原創,轉載請註明來源:http://www.jianshu.com/p/600a4e23c14e。
Java開發小技巧(四):配置文件敏感信息處理