Java微信公众号安全模式消息解密

1.微信公众平台下载解密工具,导入项目中,根据demo解密消息,解密工具官方下载地址:点击打开链接

 public static String streamToString(HttpServletRequest request) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * xml转为map集合
     *
     * @param request
     * @param msg
     * @return
     * @throws IOException
     * @throws DocumentException
     */
    public static Map xmlToMap(HttpServletRequest request, Message msg) throws Exception {
        SAXReader reader = new SAXReader();
        String token = "";
        String encodingAesKey = "";
        String appId = "";
        //获取加密消息xml字符串
      /*  String format = "";
        Document document = reader.read(request.getInputStream());
        Element rootElement = document.getRootElement();
        Element encrypt = rootElement.element("Encrypt");*/
//        String fromXML = String.format(format, encrypt.getText());
        String fromXML = streamToString(request);
        //解密消息
        WXBizMsgCrypt pc = new WXBizMsgCrypt(token, encodingAesKey, appId);
        //获得解密消息
        String result = pc.decryptMsg(msg.getMsg_signature(), msg.getTimestamp(), msg.getNonce(), fromXML);
        Map map = new HashMap<>(6);
        //将解密后的消息转为xml
        Document doc = DocumentHelper.parseText(result);
        Element root = doc.getRootElement();
        List list = root.elements();
        for (Element e : list) {
            map.put(e.getName(), e.getText());
        }
        return map;
    }

Message实体类

package com.caisin.weixin.domain;

import lombok.Data;

@Data
public class Message {
    private String signature;
    private String timestamp;
    private String nonce;
    private String openid;
    private String msg_signature;
    private String encrypt_type;
}


2.将JDK中 jdk\jre\lib\security\policy\unlimited目录中local_policy.jar和US_export_policy.jar两个文件拷贝到 jdk\jre\lib\security目录下

Java微信公众号安全模式消息解密_第1张图片



你可能感兴趣的:(Java微信公众号安全模式消息解密)