package com.chaowen; import java.io.IOException; import java.io.PrintWriter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class WeiXinServlet */ public class WeiXinServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String Token = "token"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("text/xml;charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String[] ArrTmp = { Token, timestamp, nonce }; Arrays.sort(ArrTmp); StringBuffer sb = new StringBuffer(); for (int i = 0; i < ArrTmp.length; i++) { sb.append(ArrTmp[i]); } String pwd = Encrypt(sb.toString()); String echostr = request.getParameter("echostr"); System.out.println("pwd=="+pwd); System.out.println("echostr=="+echostr); if(pwd.equals(signature)){ if(!"".equals(echostr) && echostr != null){ response.getWriter().print(echostr); } } out.flush(); out.close(); } public String Encrypt(String strSrc) { MessageDigest md = null; String strDes = null; byte[] bt = strSrc.getBytes(); try { md = MessageDigest.getInstance("SHA-1"); md.update(bt); strDes = bytes2Hex(md.digest()); //to HexString } catch (NoSuchAlgorithmException e) { System.out.println("Invalid algorithm."); return null; } return strDes; } public String bytes2Hex(byte[] bts) { String des = ""; String tmp = null; for (int i = 0; i < bts.length; i++) { tmp = (Integer.toHexString(bts[i] & 0xFF)); if (tmp.length() == 1) { des += "0"; } des += tmp; } return des; } }