这篇文章主要为大家详细介绍了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目录下
以上就是本文的全部内容,希望对大家的学习有所帮助
最后针对于互联网公司java程序员涉及到的绝大部分难题我做成了文档和架构视频资料免费分享给大家(包括Dubbo、Redis、Netty、zookeeper、Spring cloud、分布式、高并发等架构技术资料),希望能帮助到且找到一个好的工作,也节省大家在网上搜索资料的时间来学习,也可以关注我一下以后会有更多干货分享。