微信 token 验证

package org.sxl.weixin;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

public class WeiXinValidateToken {
    /**
     * 
     * @param signature
     *            微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp
     *            时间戳
     * @param nonce
     *            随机数
     * @param echostr
     *            随机字符串
     * @return 是否通过验证
     * @throws NoSuchAlgorithmException
     */
    public boolean Validate(String signature, String token, String timestamp, String nonce) throws NoSuchAlgorithmException {

        String[] array = new String[] { token, timestamp, nonce };
        StringBuffer sb = new StringBuffer();
        // 字符串排序
        Arrays.sort(array);
        for (int i = 0; i < 3; i++) {
            sb.append(array[i]);
        }
        String str = sb.toString();
        // SHA1签名生成
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        md.update(str.getBytes());
        byte[] digest = md.digest();

        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }

        if (signature.equals(hexstr)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 
     * @param request
     *            请求
     * @param token
     *            密钥
     * @return 随机数
     */
    public String ValidateRequest(HttpServletRequest request, String token) {
        String signature = request.getParameter("signature");
        String echostr = request.getParameter("echostr");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce ");
        boolean val = false;
        try {
            val = Validate(signature, token, timestamp, nonce);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(val==true){
            return echostr;
        }else{
            return "";
        }

        
    }

}

 

posted @ 2015-09-11 08:56  莫烦恼  阅读(1112)  评论(0编辑  收藏  举报