BAOLH
2025-04-27 35e30bb8dffbf5edce8a13cb5b8f91d610e198ab
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
56
57
58
59
60
61
62
63
64
65
/**
 * 对企业微信发送给企业后台的消息加解密示例代码.
 * 
 * @copyright Copyright (c) 1998-2020 Tencent Inc.
 */
 
// ------------------------------------------------------------------------
 
package me.zhengjie.utils.weixin;
 
/**
 * 针对 org.json.JSONObject,
 * 要编译打包架包json
 * 官方源码下载地址 : https://github.com/stleary/JSON-java, jar包下载地址 : https://mvnrepository.com/artifact/org.json/json
 */
import org.json.JSONObject;
 
 
/**
 * JsonParse class
 *
 * 提供提取消息格式中的密文及生成回复消息格式的接口.
 */
class JsonParse {
 
    /**
     * 提取出 JSON 包中的加密消息
     * @param jsontext 待提取的json字符串
     * @return 提取出的加密消息字符串
     * @throws AesException 
     */
    public static Object[] extract(String jsontext) throws AesException     {
        Object[] result = new Object[3];
        try {
 
            JSONObject json = new JSONObject(jsontext);    
            String encrypt_msg = json.getString("encrypt");
            String tousername  = json.getString("tousername");
            String agentid     = json.getString("agentid");
 
            result[0] = tousername;
            result[1] = encrypt_msg;
            result[2] = agentid;
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ParseJsonError);
        }
    }
 
    /**
     * 生成json消息
     * @param encrypt 加密后的消息密文
     * @param signature 安全签名
     * @param timestamp 时间戳
     * @param nonce 随机字符串
     * @return 生成的json字符串
     */
    public static String generate(String encrypt, String signature, String timestamp, String nonce) {
 
        String format = "{\"encrypt\":\"%1$s\",\"msgsignature\":\"%2$s\",\"timestamp\":\"%3$s\",\"nonce\":\"%4$s\"}";
        return String.format(format, encrypt, signature, timestamp, nonce);
 
    }
}