您的位置:首页 > 移动开发 > 微信开发

java 微信开发token验证失败的一种情况

2016-09-03 15:53 405 查看
用java做微信开发,验证token时怎么尝试总是失败,于是把每一步获取和计算参数都打印出来看看到底发生了什么。

这是源代码

doGet 方法:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");

PrintWriter out = response.getWriter();
if (CheckUtil.checkSignature(signature, timestamp, nonce)){
System.out.println("check ok");
out.print(echostr);

}
out.close();
}

check util:

public static boolean checkSignature(String signature, String timestamp,
String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// sort
Arrays.sort(arr);

// generate String
String content = arr[0]+arr[1]+arr[2];

// shal code
String temp = new SHA1().getDigestOfString(content.getBytes());

return temp.equalsIgnoreCase(signature);
}

思想其实就是获取到参数 timestamp, nonce 和自己定义的 参数 token一起排序,然后生成一个它们排序后的新字符串,然后给这个字符串用SHA1加密,如果加密结果和获取到的参数 signature相等,则返回获得的参数 echostr。

刚开始我比较获得的参数,加密后怎么看都与 signature 相等,但是验证信息却总是发现不等,后来发现问题在大小写字母上,我使用的SHA1加密后返回的是大写字母,于是在比较的时候改为“temp.equalsIgnoreCase(signature)”忽略大小写比较后,果然通过验证。\(^o^)/~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 微信 token验证