Java微信公众号安全模式消息解密
作者:Caisin_He
这篇文章主要为大家详细介绍了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目录下
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。