时间:2020-10-08 13:29:17 | 栏目:JAVA代码 | 点击:次
本文实例为大家分享了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<String, String> xmlToMap(HttpServletRequest request, Message msg) throws Exception { SAXReader reader = new SAXReader(); String token = ""; String encodingAesKey = ""; String appId = ""; //获取加密消息xml字符串 /* String format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%1$s]]></Encrypt></xml>"; 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<String, String> map = new HashMap<>(6); //将解密后的消息转为xml Document doc = DocumentHelper.parseText(result); Element root = doc.getRootElement(); List<Element> 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目录下