E1ED922C1E9526DD63272D7EC5C6CB77
2021-02-07 2ad84337e1ae42b56a7b8e463bca9ac06e457826
提交 | 用户 | age
5c5945 1 /**
E 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.security.MessageDigest;
12 import java.util.Arrays;
13
14 /**
15  * SHA1 class
16  *
17  * 计算消息签名接口.
18  */
19 class SHA1 {
20
21     /**
22      * 用SHA1算法生成安全签名
23      * @param token 票据
24      * @param timestamp 时间戳
25      * @param nonce 随机字符串
26      * @param encrypt 密文
27      * @return 安全签名
28      * @throws AesException 
29      */
30     public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException
31               {
32         try {
33             String[] array = new String[] { token, timestamp, nonce, encrypt };
34             StringBuffer sb = new StringBuffer();
35             // 字符串排序
36             Arrays.sort(array);
37             for (int i = 0; i < 4; i++) {
38                 sb.append(array[i]);
39             }
40             String str = sb.toString();
41             // SHA1签名生成
42             MessageDigest md = MessageDigest.getInstance("SHA-1");
43             md.update(str.getBytes());
44             byte[] digest = md.digest();
45
46             StringBuffer hexstr = new StringBuffer();
47             String shaHex = "";
48             for (int i = 0; i < digest.length; i++) {
49                 shaHex = Integer.toHexString(digest[i] & 0xFF);
50                 if (shaHex.length() < 2) {
51                     hexstr.append(0);
52                 }
53                 hexstr.append(shaHex);
54             }
55             return hexstr.toString();
56         } catch (Exception e) {
57             e.printStackTrace();
58             throw new AesException(AesException.ComputeSignatureError);
59         }
60     }
61 }