Java开发小技巧(四):配置文件敏感信息处理

AES(高级加密标准)是美国联邦政府采用的一种区块加密标准,其替代原先的DES加密算法,成为对称密钥加密中最流行的算法之一。

不知道在上一篇文章中你有没有发现,jdbc.properties中的数据库密码配置是这样写的:

1
jdbc.password=5EF28C5A9A0CE86C2D231A526ED5B388

其实这不是真正的密码,而是经过AES加密的。

AES的Java实现

AES加密解密的实现就不具体介绍了,这里直接给出源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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,然后重写它的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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修改为我们创建的类即可:

1
2
3
4
5
6
<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原创,转载请注明来源:https://zkhdev.github.io/2017/12/22/java-dev4/