提交 | 用户 | age
|
5c5945
|
1 |
/** |
E |
2 |
* 对企业微信发送给企业后台的消息加解密示例代码. |
|
3 |
* |
|
4 |
* @copyright Copyright (c) 1998-2014 Tencent Inc. |
|
5 |
*/ |
|
6 |
|
|
7 |
// ------------------------------------------------------------------------ |
|
8 |
|
|
9 |
/** |
|
10 |
* 针对org.apache.commons.codec.binary.Base64, |
|
11 |
* 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本) |
|
12 |
* 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi |
|
13 |
*/ |
|
14 |
package com.qq.weixin.mp.aes; |
|
15 |
|
|
16 |
import java.nio.charset.Charset; |
|
17 |
import java.util.Arrays; |
|
18 |
import java.util.Random; |
|
19 |
|
|
20 |
import javax.crypto.Cipher; |
|
21 |
import javax.crypto.spec.IvParameterSpec; |
|
22 |
import javax.crypto.spec.SecretKeySpec; |
|
23 |
|
|
24 |
import org.apache.commons.codec.binary.Base64; |
|
25 |
import org.slf4j.Logger; |
|
26 |
import org.slf4j.LoggerFactory; |
|
27 |
|
|
28 |
/** |
|
29 |
* 提供接收和推送给企业微信消息的加解密接口(UTF8编码的字符串). |
|
30 |
* <ol> |
|
31 |
* <li>第三方回复加密消息给企业微信</li> |
|
32 |
* <li>第三方收到企业微信发送的消息,验证消息的安全性,并对消息进行解密。</li> |
|
33 |
* </ol> |
|
34 |
* 说明:异常java.security.InvalidKeyException:illegal Key Size的解决方案 |
|
35 |
* <ol> |
|
36 |
* <li>在官方网站下载JCE无限制权限策略文件(JDK7的下载地址: |
|
37 |
* http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</li> |
|
38 |
* <li>下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt</li> |
|
39 |
* <li>如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件</li> |
|
40 |
* <li>如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件</li> |
|
41 |
* </ol> |
|
42 |
*/ |
|
43 |
public class WXBizMsgCrypt { |
|
44 |
|
|
45 |
//log4j日志 |
|
46 |
private static Logger logger = LoggerFactory.getLogger(WXBizMsgCrypt.class.getName()); |
|
47 |
|
|
48 |
static Charset CHARSET = Charset.forName("utf-8"); |
|
49 |
Base64 base64 = new Base64(); |
|
50 |
byte[] aesKey; |
|
51 |
String token; |
|
52 |
String receiveid; |
|
53 |
|
|
54 |
/** |
|
55 |
* 构造函数 |
|
56 |
* @param token 企业微信后台,开发者设置的token |
|
57 |
* @param encodingAesKey 企业微信后台,开发者设置的EncodingAESKey |
|
58 |
* @param receiveid, 不同场景含义不同,详见文档 |
|
59 |
* |
|
60 |
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息 |
|
61 |
*/ |
|
62 |
public WXBizMsgCrypt(String token, String encodingAesKey, String receiveid) throws AesException { |
|
63 |
if (encodingAesKey.length() != 43) { |
|
64 |
throw new AesException(AesException.IllegalAesKey); |
|
65 |
} |
|
66 |
|
|
67 |
this.token = token; |
|
68 |
this.receiveid = receiveid; |
|
69 |
aesKey = Base64.decodeBase64(encodingAesKey + "="); |
|
70 |
} |
|
71 |
|
|
72 |
// 生成4个字节的网络字节序 |
|
73 |
byte[] getNetworkBytesOrder(int sourceNumber) { |
|
74 |
byte[] orderBytes = new byte[4]; |
|
75 |
orderBytes[3] = (byte) (sourceNumber & 0xFF); |
|
76 |
orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF); |
|
77 |
orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF); |
|
78 |
orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF); |
|
79 |
return orderBytes; |
|
80 |
} |
|
81 |
|
|
82 |
// 还原4个字节的网络字节序 |
|
83 |
int recoverNetworkBytesOrder(byte[] orderBytes) { |
|
84 |
int sourceNumber = 0; |
|
85 |
for (int i = 0; i < 4; i++) { |
|
86 |
sourceNumber <<= 8; |
|
87 |
sourceNumber |= orderBytes[i] & 0xff; |
|
88 |
} |
|
89 |
return sourceNumber; |
|
90 |
} |
|
91 |
|
|
92 |
// 随机生成16位字符串 |
|
93 |
String getRandomStr() { |
|
94 |
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; |
|
95 |
Random random = new Random(); |
|
96 |
StringBuffer sb = new StringBuffer(); |
|
97 |
for (int i = 0; i < 16; i++) { |
|
98 |
int number = random.nextInt(base.length()); |
|
99 |
sb.append(base.charAt(number)); |
|
100 |
} |
|
101 |
return sb.toString(); |
|
102 |
} |
|
103 |
|
|
104 |
/** |
|
105 |
* 对明文进行加密. |
|
106 |
* |
|
107 |
* @param text 需要加密的明文 |
|
108 |
* @return 加密后base64编码的字符串 |
|
109 |
* @throws AesException aes加密失败 |
|
110 |
*/ |
|
111 |
String encrypt(String randomStr, String text) throws AesException { |
|
112 |
ByteGroup byteCollector = new ByteGroup(); |
|
113 |
byte[] randomStrBytes = randomStr.getBytes(CHARSET); |
|
114 |
byte[] textBytes = text.getBytes(CHARSET); |
|
115 |
byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); |
|
116 |
byte[] receiveidBytes = receiveid.getBytes(CHARSET); |
|
117 |
|
|
118 |
// randomStr + networkBytesOrder + text + receiveid |
|
119 |
byteCollector.addBytes(randomStrBytes); |
|
120 |
byteCollector.addBytes(networkBytesOrder); |
|
121 |
byteCollector.addBytes(textBytes); |
|
122 |
byteCollector.addBytes(receiveidBytes); |
|
123 |
|
|
124 |
// ... + pad: 使用自定义的填充方式对明文进行补位填充 |
|
125 |
byte[] padBytes = PKCS7Encoder.encode(byteCollector.size()); |
|
126 |
byteCollector.addBytes(padBytes); |
|
127 |
|
|
128 |
// 获得最终的字节流, 未加密 |
|
129 |
byte[] unencrypted = byteCollector.toBytes(); |
|
130 |
|
|
131 |
try { |
|
132 |
// 设置加密模式为AES的CBC模式 |
|
133 |
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); |
|
134 |
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES"); |
|
135 |
IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16); |
|
136 |
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); |
|
137 |
|
|
138 |
// 加密 |
|
139 |
byte[] encrypted = cipher.doFinal(unencrypted); |
|
140 |
|
|
141 |
// 使用BASE64对加密后的字符串进行编码 |
|
142 |
String base64Encrypted = base64.encodeToString(encrypted); |
|
143 |
|
|
144 |
return base64Encrypted; |
|
145 |
} catch (Exception e) { |
|
146 |
e.printStackTrace(); |
|
147 |
throw new AesException(AesException.EncryptAESError); |
|
148 |
} |
|
149 |
} |
|
150 |
|
|
151 |
/** |
|
152 |
* 对密文进行解密. |
|
153 |
* |
|
154 |
* @param text 需要解密的密文 |
|
155 |
* @return 解密得到的明文 |
|
156 |
* @throws AesException aes解密失败 |
|
157 |
*/ |
|
158 |
String decrypt(String text) throws AesException { |
|
159 |
byte[] original; |
|
160 |
try { |
|
161 |
// 设置解密模式为AES的CBC模式 |
|
162 |
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); |
|
163 |
SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES"); |
|
164 |
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16)); |
|
165 |
cipher.init(Cipher.DECRYPT_MODE, key_spec, iv); |
|
166 |
|
|
167 |
// 使用BASE64对密文进行解码 |
|
168 |
byte[] encrypted = Base64.decodeBase64(text); |
|
169 |
|
|
170 |
// 解密 |
|
171 |
original = cipher.doFinal(encrypted); |
|
172 |
} catch (Exception e) { |
|
173 |
logger.info("aes解密报错:",e); |
|
174 |
e.printStackTrace(); |
|
175 |
throw new AesException(AesException.DecryptAESError); |
|
176 |
} |
|
177 |
|
|
178 |
String xmlContent, from_receiveid; |
|
179 |
try { |
|
180 |
// 去除补位字符 |
|
181 |
byte[] bytes = PKCS7Encoder.decode(original); |
|
182 |
|
|
183 |
// 分离16位随机字符串,网络字节序和receiveid |
|
184 |
byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20); |
|
185 |
|
|
186 |
int xmlLength = recoverNetworkBytesOrder(networkOrder); |
|
187 |
|
|
188 |
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET); |
|
189 |
from_receiveid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), |
|
190 |
CHARSET); |
|
191 |
} catch (Exception e) { |
|
192 |
e.printStackTrace(); |
|
193 |
throw new AesException(AesException.IllegalBuffer); |
|
194 |
} |
|
195 |
|
|
196 |
// receiveid不相同的情况 |
|
197 |
if (!from_receiveid.equals(receiveid)) { |
|
198 |
throw new AesException(AesException.ValidateCorpidError); |
|
199 |
} |
|
200 |
return xmlContent; |
|
201 |
|
|
202 |
} |
|
203 |
|
|
204 |
/** |
|
205 |
* 将企业微信回复用户的消息加密打包. |
|
206 |
* <ol> |
|
207 |
* <li>对要发送的消息进行AES-CBC加密</li> |
|
208 |
* <li>生成安全签名</li> |
|
209 |
* <li>将消息密文和安全签名打包成xml格式</li> |
|
210 |
* </ol> |
|
211 |
* |
|
212 |
* @param replyMsg 企业微信待回复用户的消息,xml格式的字符串 |
|
213 |
* @param timeStamp 时间戳,可以自己生成,也可以用URL参数的timestamp |
|
214 |
* @param nonce 随机串,可以自己生成,也可以用URL参数的nonce |
|
215 |
* |
|
216 |
* @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串 |
|
217 |
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息 |
|
218 |
*/ |
|
219 |
public String EncryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException { |
|
220 |
// 加密 |
|
221 |
String encrypt = encrypt(getRandomStr(), replyMsg); |
|
222 |
|
|
223 |
// 生成安全签名 |
|
224 |
if (timeStamp == "") { |
|
225 |
timeStamp = Long.toString(System.currentTimeMillis()); |
|
226 |
} |
|
227 |
|
|
228 |
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt); |
|
229 |
|
|
230 |
// System.out.println("发送给平台的签名是: " + signature[1].toString()); |
|
231 |
// 生成发送的xml |
|
232 |
String result = XMLParse.generate(encrypt, signature, timeStamp, nonce); |
|
233 |
return result; |
|
234 |
} |
|
235 |
|
|
236 |
/** |
|
237 |
* 检验消息的真实性,并且获取解密后的明文. |
|
238 |
* <ol> |
|
239 |
* <li>利用收到的密文生成安全签名,进行签名验证</li> |
|
240 |
* <li>若验证通过,则提取xml中的加密消息</li> |
|
241 |
* <li>对消息进行解密</li> |
|
242 |
* </ol> |
|
243 |
* |
|
244 |
* @param msgSignature 签名串,对应URL参数的msg_signature |
|
245 |
* @param timeStamp 时间戳,对应URL参数的timestamp |
|
246 |
* @param nonce 随机串,对应URL参数的nonce |
|
247 |
* @param postData 密文,对应POST请求的数据 |
|
248 |
* |
|
249 |
* @return 解密后的原文 |
|
250 |
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息 |
|
251 |
*/ |
|
252 |
public String DecryptMsg(String msgSignature, String timeStamp, String nonce, String postData) |
|
253 |
throws AesException { |
|
254 |
|
|
255 |
// 密钥,公众账号的app secret |
|
256 |
// 提取密文 |
|
257 |
Object[] encrypt = XMLParse.extract(postData); |
|
258 |
|
|
259 |
// 验证安全签名 |
|
260 |
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString()); |
|
261 |
|
|
262 |
// 和URL中的签名比较是否相等 |
|
263 |
// System.out.println("第三方收到URL中的签名:" + msg_sign); |
|
264 |
// System.out.println("第三方校验签名:" + signature); |
|
265 |
if (!signature.equals(msgSignature)) { |
|
266 |
throw new AesException(AesException.ValidateSignatureError); |
|
267 |
} |
|
268 |
|
|
269 |
// 解密 |
|
270 |
String result = decrypt(encrypt[1].toString()); |
|
271 |
return result; |
|
272 |
} |
|
273 |
|
|
274 |
/** |
|
275 |
* 验证URL |
|
276 |
* @param msgSignature 签名串,对应URL参数的msg_signature |
|
277 |
* @param timeStamp 时间戳,对应URL参数的timestamp |
|
278 |
* @param nonce 随机串,对应URL参数的nonce |
|
279 |
* @param echoStr 随机串,对应URL参数的echostr |
|
280 |
* |
|
281 |
* @return 解密之后的echostr |
|
282 |
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息 |
|
283 |
*/ |
|
284 |
public String VerifyURL(String msgSignature, String timeStamp, String nonce, String echoStr) |
|
285 |
throws AesException { |
|
286 |
String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr); |
|
287 |
|
|
288 |
if (!signature.equals(msgSignature)) { |
|
289 |
throw new AesException(AesException.ValidateSignatureError); |
|
290 |
} |
|
291 |
|
|
292 |
String result = decrypt(echoStr); |
|
293 |
return result; |
|
294 |
} |
|
295 |
|
|
296 |
} |