java 检验signature_java下的token校验

开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带四个参数:

参数

描述

signature

微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。

timestamp

时间戳

nonce

随机数

echostr

随即字符串

开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。

加密/校验流程如下:

1. 将token、timestamp、nonce三个参数进行字典序排序

2. 将三个参数字符串拼接成一个字符串进行sha1加密

3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信

Java代码:

public class SignUtil {

private static String token = "weixin";

public static boolean checkSignature(String signature, String timestamp, String nonce) {

boolean result = false;

// 对token、timestamp和nonce按字典序排序

String[] array = new String[]{token, timestamp, nonce};

Arrays.sort(array);

// 将三个参数字符拼接成一个字符串

String str = array[0].concat(array[1]).concat(array[2]);

String sha1Str = null;

try {

// 对拼接后的字符串进行sha1加密

MessageDigest md = MessageDigest.getInstance("SHA-1");

byte[] digest = md.digest(str.getBytes());

sha1Str = byte2str(digest);

}

catch(Exception e) {

}

if(sha1Str != null && sha1Str.equals(signature)) {

result = true;

}

return result;

}

/*

* 将字节数组转换成字符串

*/

public static String byte2str(byte[] array) {

StringBuffer hexstr = new StringBuffer();

String shaHex="";

for(int i = 0; i < array.length; i++) {

shaHex = Integer.toHexString(array[i] & 0xFF);

if(shaHex.length() < 2) {

hexstr.append(0);

}

hexstr.append(shaHex);

}

return hexstr.toString();

}

}

原文:http://blog.csdn.net/huai814586181/article/details/51347320

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值