1 /**
2 * 对公众平台发送给公众账号的消息加解密示例代码.
3 *
4 * @copyright Copyright (c) 1998-2014 Tencent Inc.
5 */
6
7 // ------------------------------------------------------------------------
8
9 package com.zone.weixin4j.util;
10
11 import java.util.Arrays;
12
13 /**
14 * 提供基于PKCS7算法的加解密接口</br>
15 * 提供接收和推送给公众平台消息的加解密接口(UTF8编码的字符串).
16 * <ol>
17 * <li>第三方回复加密消息给公众平台</li>
18 * <li>第三方收到公众平台发送的消息,验证消息的安全性,并对消息进行解密。</li>
19 * </ol>
20 * 说明:异常java.security.InvalidKeyException:illegal Key Size的解决方案
21 * <ol>
22 * <li>在官方网站下载JCE无限制权限策略文件(JDK7的下载地址:
23 * http://www.oracle.com/technetwork/java/javase
24 * /downloads/jce-7-download-432124.html</li>
25 * <li>下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt</li>
26 * <li>如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件</li>
27 * <li>如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件</li>
28 * </ol>
29 */
30 public class PKCS7Encoder {
31 private final static int BLOCK_SIZE = 32;
32
33 /**
34 * 获得对明文进行补位填充的字节.
35 *
36 * @param count
37 * 需要进行填充补位操作的明文字节个数
38 * @return 补齐用的字节数组
39 */
40 public static byte[] encode(int count) {
41 // 计算需要填充的位数
42 int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
43 if (amountToPad == 0) {
44 amountToPad = BLOCK_SIZE;
45 }
46 // 获得补位所用的字符
47 byte target = (byte) (amountToPad & 0xFF);
48 char padChr = (char) target;
49 StringBuilder tmp = new StringBuilder();
50 for (int index = 0; index < amountToPad; index++) {
51 tmp.append(padChr);
52 }
53 return tmp.toString().getBytes(ServerToolkits.UTF_8);
54 }
55
56 /**
57 * 删除解密后明文的补位字符
58 *
59 * @param decrypted
60 * 解密后的明文
61 * @return 删除补位字符后的明文
62 */
63 public static byte[] decode(byte[] decrypted) {
64 int pad = (int) decrypted[decrypted.length - 1];
65 if (pad < 1 || pad > 32) {
66 pad = 0;
67 }
68 return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
69 }
70 }