提交 | 用户 | age
|
826b66
|
1 |
/** |
C |
2 |
* 对企业微信发送给企业后台的消息加解密示例代码. |
|
3 |
* |
|
4 |
* @copyright Copyright (c) 1998-2014 Tencent Inc. |
|
5 |
*/ |
|
6 |
|
|
7 |
// ------------------------------------------------------------------------ |
|
8 |
|
|
9 |
package com.qq.weixin.mp.aes; |
|
10 |
|
|
11 |
import java.nio.charset.Charset; |
|
12 |
import java.util.Arrays; |
|
13 |
|
|
14 |
/** |
|
15 |
* 提供基于PKCS7算法的加解密接口. |
|
16 |
*/ |
|
17 |
class PKCS7Encoder { |
|
18 |
static Charset CHARSET = Charset.forName("utf-8"); |
|
19 |
static int BLOCK_SIZE = 32; |
|
20 |
|
|
21 |
/** |
|
22 |
* 获得对明文进行补位填充的字节. |
|
23 |
* |
|
24 |
* @param count 需要进行填充补位操作的明文字节个数 |
|
25 |
* @return 补齐用的字节数组 |
|
26 |
*/ |
|
27 |
static byte[] encode(int count) { |
|
28 |
// 计算需要填充的位数 |
|
29 |
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE); |
|
30 |
if (amountToPad == 0) { |
|
31 |
amountToPad = BLOCK_SIZE; |
|
32 |
} |
|
33 |
// 获得补位所用的字符 |
|
34 |
char padChr = chr(amountToPad); |
|
35 |
String tmp = new String(); |
|
36 |
for (int index = 0; index < amountToPad; index++) { |
|
37 |
tmp += padChr; |
|
38 |
} |
|
39 |
return tmp.getBytes(CHARSET); |
|
40 |
} |
|
41 |
|
|
42 |
/** |
|
43 |
* 删除解密后明文的补位字符 |
|
44 |
* |
|
45 |
* @param decrypted 解密后的明文 |
|
46 |
* @return 删除补位字符后的明文 |
|
47 |
*/ |
|
48 |
static byte[] decode(byte[] decrypted) { |
|
49 |
int pad = (int) decrypted[decrypted.length - 1]; |
|
50 |
if (pad < 1 || pad > 32) { |
|
51 |
pad = 0; |
|
52 |
} |
|
53 |
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad); |
|
54 |
} |
|
55 |
|
|
56 |
/** |
|
57 |
* 将数字转化成ASCII码对应的字符,用于对明文进行补码 |
|
58 |
* |
|
59 |
* @param a 需要转化的数字 |
|
60 |
* @return 转化得到的字符 |
|
61 |
*/ |
|
62 |
static char chr(int a) { |
|
63 |
byte target = (byte) (a & 0xFF); |
|
64 |
return (char) target; |
|
65 |
} |
|
66 |
|
|
67 |
} |