WxaBizDataCrypt.java
1.7 KB
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
/**
* Copyright (c) 2011-2014, L.cm 卢春梦 (qq596392912@gmail.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jfinal.weixin.sdk.encrypt;
import com.jfinal.weixin.sdk.utils.Base64Utils;
import com.jfinal.weixin.sdk.utils.Charsets;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Key;
/**
* 微信小程序-加密数据解密算法
* @author L.cm
*/
public class WxaBizDataCrypt {
private final String sessionKey;
public WxaBizDataCrypt(String sessionKey) {
this.sessionKey = sessionKey;
}
/**
* AES解密
* @param encryptedData 密文
* @param ivStr iv
* @return {String}
*/
public String decrypt(String encryptedData, String ivStr) {
byte[] bizData = Base64Utils.decodeBase64(encryptedData);
byte[] keyByte = Base64Utils.decodeBase64(sessionKey);
byte[] ivByte = Base64Utils.decodeBase64(ivStr);
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
Key sKeySpec = new SecretKeySpec(keyByte, "AES");
// 初始化
AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
params.init(new IvParameterSpec(ivByte));
cipher.init(Cipher.DECRYPT_MODE, sKeySpec, params);
byte[] original = cipher.doFinal(bizData);
// 去除补位字符
byte[] result = PKCS7Encoder.decode(original);
return new String(result, Charsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("aes解密失败");
}
}
}