微信公衆平臺第三方平臺全網發佈 java

小弟初次寫,寫的不好,大神多多關照

總共分爲兩部分:

1.授權,微信每10分鐘會給第三方平臺推送一次,這裏有需要用到的 COMPONENT_VERIFY_TICKET,並且需要響應 success。

請求的內容(通過request.getParameter()可以取到):

msg_signature、signature、timestamp、nonce

請求內容主體(通過流的方式可以讀取):

<xml>    <AppId><![CDATA[wxde4c1]]></AppId>    <Encrypt><![CDATA[AjNYHkpxXdv99o/AV0HyklxjMFtPpRlP1VGKiAm92dyUusRZ8tpuzxBocKxtOFV04NABs7vchuRM2sBTjvb8emGMRDmhHGkMeb9933Usl8eOcFo60yj32BnxkxrmRUx8BeNRtAu98qfE72kfsUsbTyZE9FHp2xNjM75KEq8jh29eK/Rt6GVadzz9DO+qSEu+XRB0A3m5CzQ6nYDyTwDz7w01kKhx9PBHFBvnkh3p4bWV3ATNPR5+xm5/z0p8O6VGMeWkhv7XjGgk3WPcHYRtZMn/CZB2aKuxsosl3MCr1OADLLSJ+J4vGNdShMxLmUSJKR7E8SANFZUOiKOMFPmh62x3sJu4PXaLX15kzfT8DB1A3BW6g/ErEE9n+c3N4MIUW/ac/5sKeG7IjsJOgH3tfJfG4qSYuOyBKbqFyWqaZWxW/L+M=]]></Encrypt></xml>

需要注意的是,並不是整個xml都加密,只是加密了<Encrypt></Encrypt>

解密後可以得到新的xml:

<xml><AppId><![CDATA[wxde71bfe4c1]]></AppId>
<CreateTime>1558420435</CreateTime>
<InfoType><![CDATA[componencket]]></InfoType>
<ComponentVerifyTicket><![CDATA[ticket@@@DVkcsSTOEjZIwpJe5Wzwx9eZM1eZVQnzi2Y3KrorUL8vg]]></ComponentVerifyTicket>
</xml>

其中<ComponentVerifyTicket>是我們需要的ticket(建議緩存起來),需要注意的是ticket@@@需要接去掉。

2.文本消息和事件消息

文本消息分爲兩種:a.固定內容  b.不響應,使用客服消息

代碼:

@RestController
@RequestMapping("/wx")
public class WxController {
    /**
     * 微信全網測試賬號
     */
    private final static String COMPONENT_APPID = "";//第三方平臺APPID
    private final String COMPONENT_APPSECRET = "";//第三方平臺APPSECRET
    private final static String COMPONENT_ENCODINGAESKEY = "";//消息加解密Key
    private final static String COMPONENT_TOKEN = "";//消息校驗Token


    /**
     * 消息和事件
     * 消息與事件接收URL   http://xxxxxxx/nrm/wx/$APPID$/callback
     * @throws IOException
     */
    @RequestMapping("/{appid}/callback")
    public void acceptMessageAndEvent(HttpServletRequest request, HttpServletResponse response) throws DocumentException, IOException, AesException {
        System.out.println("--------------------------------微信公衆號第三方平臺全網發佈---------------------------------------");
        System.out.println("--------------------------------普通消息和事件消息--------------------------------");
        System.out.println("--------------------------------驗證 msg_signature--------------------------------");
        String msgSignature = request.getParameter("msg_signature");
        System.out.println("msg_signature=" + msgSignature);

        if (!StringUtils.isNotBlank(msgSignature))
            return;// 微信推送給第三方開放平臺的消息一定是加過密的,無消息加密無法解密消息

        StringBuilder sb = new StringBuilder();
        BufferedReader in = request.getReader();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();
        String xml = sb.toString();

        System.out.println("--------------------------------接收到請求內容(加密)--------------------------------");
        System.out.println("--------------------------------原始 xml=" + xml);
        checkWeixinAllNetworkCheck(request,response,xml);
    }



    public void checkWeixinAllNetworkCheck(HttpServletRequest request, HttpServletResponse response,String xml) throws DocumentException, IOException, AesException{
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String msgSignature = request.getParameter("msg_signature");

        WXBizMsgCrypt pc = new WXBizMsgCrypt(COMPONENT_TOKEN, COMPONENT_ENCODINGAESKEY, COMPONENT_APPID);
        xml = pc.decryptMsg(msgSignature, timestamp, nonce, xml);
        System.out.println("--------------------------------解密  xml=" + xml);


        Document doc = DocumentHelper.parseText(xml);
        Element rootElt = doc.getRootElement();
        String msgType = rootElt.elementText("MsgType");
        String toUserName = rootElt.elementText("ToUserName");
        String fromUserName = rootElt.elementText("FromUserName");

        if("event".equals(msgType)){
            String event = rootElt.elementText("Event");
            replyEventMessage(request,response,event,toUserName,fromUserName);
        }else if("text".equals(msgType)){
            String content = rootElt.elementText("Content");
            processTextMessage(request,response,content,toUserName,fromUserName);
        }
    }

    /**
     * 文本消息處理
     * @param request       請求
     * @param response      響應
     * @param content       消息內容
     * @param toUserName    微信公衆號
     * @param fromUserName  微信粉絲
     * @throws IOException
     * @throws DocumentException
     */
    public void processTextMessage(HttpServletRequest request, HttpServletResponse response,String content,String toUserName, String fromUserName) throws IOException, DocumentException{
        if("TESTCOMPONENT_MSG_TYPE_TEXT".equals(content)){
            //固定請求內容,直接返回
            String returnContent = content+"_callback";
            replyTextMessage(request,response,returnContent,toUserName,fromUserName);
        }else if(StringUtils.startsWithIgnoreCase(content, "QUERY_AUTH_CODE")){
            //固定內容,響應後需要客服主動發送一條消息給微信粉絲(不需要加密)
            output(response, "");
            //接下來客服API再回復一次消息
            replyApiTextMessage(request,response,content.split(":")[1],fromUserName);
        }
    }


    /**
     * 回覆事件消息
     * @param request
     * @param response
     * @param event
     * @param toUserName
     * @param fromUserName
     * @throws DocumentException
     * @throws IOException
     */
    public void replyEventMessage(HttpServletRequest request, HttpServletResponse response, String event, String toUserName, String fromUserName) throws DocumentException, IOException {
        System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&回覆事件消息&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
        String content = event + "from_callback";
        replyTextMessage(request,response,content,toUserName,fromUserName);
    }



    /**
     * 回覆微信服務器"文本消息"
     * @param request           請求
     * @param response          響應
     * @param content           內容
     * @param toUserName        微信公衆號
     * @param fromUserName      微信粉絲
     * @throws DocumentException
     * @throws IOException
     */
    public void replyTextMessage(HttpServletRequest request, HttpServletResponse response, String content, String toUserName, String fromUserName) throws DocumentException, IOException {
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!回覆微信的文本消息!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        Long createTime = System.currentTimeMillis();
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        sb.append("<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>");
        sb.append("<FromUserName><![CDATA["+toUserName+"]]></FromUserName>");
        sb.append("<CreateTime>"+createTime+"</CreateTime>");
        sb.append("<MsgType><![CDATA[text]]></MsgType>");
        sb.append("<Content><![CDATA["+content+"]]></Content>");
        sb.append("</xml>");
        String replyMsg = sb.toString();

        String returnvaleue = "";
        try {
            WXBizMsgCrypt pc = new WXBizMsgCrypt(COMPONENT_TOKEN, COMPONENT_ENCODINGAESKEY, COMPONENT_APPID);
            returnvaleue = pc.encryptMsg(replyMsg, createTime.toString(), "easemob");
        } catch (AesException e) {
            e.printStackTrace();
        }
        output(response, returnvaleue);
    }


    /**
     * 發送客服消息
     * @param auth_code     授權碼
     * @param fromUserName
     * @throws DocumentException
     * @throws IOException
     */
    public void replyApiTextMessage(HttpServletRequest request, HttpServletResponse response, String auth_code, String fromUserName) throws DocumentException, IOException {
        System.out.println("##############################################發送客服消息##############################################");
        CloseableHttpClient client = null;
        CloseableHttpResponse response1 = null;
        try {
            RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
            String authorizer_access_token = (String) redisUtil.get("so_release_access_token");
            if(authorizer_access_token == null || "".equals(authorizer_access_token))
                authorizer_access_token = getAuthorizerAccessToken(auth_code);
            System.out.println("##################################access_token#################################" + authorizer_access_token);
            String param = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + auth_code + "_from_api\"}}";

            System.out.println("###################################請求主體#####################################" + param);

            HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + authorizer_access_token);
            post.setHeader("Content-Type","application/json");
            post.setEntity(new StringEntity(param));

            client = HttpClients.createDefault();
            response1 = client.execute(post);
            if(response1 != null && response1.getEntity() != null){
                String result = EntityUtils.toString(response1.getEntity(), "UTF-8");
                System.out.println("###############################發送客服消息響應結果:" + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(response1 != null){
                response1.close();
            }
            if(client != null){
                client.close();
            }
        }
    }


//---------------------------------------------------------------以上是文本消息、普通消息和事件消息----------------------------------------------------------------------------------


    /**
     * 授權,獲取component_verify_ticket
     * 此請求的連接需要和微信公衆號第三方平臺,開發資料,授權事件接收URL保持一致,可以獲取到  COMPONENT_VERIFY_TICKET
     * 需要響應給微信success
     * 授權事件接收URL: http://xxxxxxxx/nrm/wx/authorization
     */
    @RequestMapping("/authorization")
    public void authorization(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException, AesException {
        System.out.println("********************************微信第三方平臺  授權推送事件********************************");
        processAuthorizeEvent(request);
        output(response, "success");
    }

    /**
     * 處理授權事件的推送
     */
    public void processAuthorizeEvent(HttpServletRequest request) throws IOException, DocumentException, AesException {
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String signature = request.getParameter("signature");
        String msgSignature = request.getParameter("msg_signature");


        if (!StringUtils.isNotBlank(msgSignature))
            return;// 微信推送給第三方開放平臺的消息一定是加過密的,無消息加密無法解密消息
        boolean isValid = checkSignature(COMPONENT_TOKEN, signature, timestamp, nonce);
        if (isValid) {
            StringBuilder sb = new StringBuilder();
            BufferedReader in = request.getReader();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            String xml = sb.toString();
            System.out.println("********************************解密前 xml=" + xml);
            WXBizMsgCrypt pc = new WXBizMsgCrypt(COMPONENT_TOKEN, COMPONENT_ENCODINGAESKEY, COMPONENT_APPID);
            Map<String, String> requestMap = XmlUtil.xmlToMap(xml);
            xml = pc.decrypt(requestMap.get("Encrypt"));
            System.out.println("********************************解密後 xml=" + xml);
            processAuthorizationEvent(xml);
        }
    }

    /**
     * 獲取第三方平臺component_access_token
     * 根據component_appid、component_appsecret(即在微信開放平臺管理中心的第三方平臺詳情頁中appId和appsecret)
     * 和component_verify_ticket來獲取自己的接口調用憑證(component_access_token)
     * component_access_token 有效期2小時
     * @return
     */
    String getAccessToken(){
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
            String param = "{\"component_appid\":\"" + COMPONENT_APPID + "\",\"component_appsecret\":\"" + COMPONENT_APPSECRET + "\",\"component_verify_ticket\":\"" + (String)redisUtil.get("component_verify_ticket") + "\"}";
            HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_component_token");
            post.setHeader("Content-Type","application/json");
            post.setEntity(new StringEntity(param));

            client = HttpClients.createDefault();
            response = client.execute(post);
            if(response != null && response.getEntity() != null){
                JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
                return result.getString("component_access_token");
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 獲取預授權碼pre_auth_code
     * @return
     */
    String getPreAuthCode(){
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try{
            String component_access_token = getAccessToken();
            if(Strings.isNotEmpty(component_access_token)) {
                String parame = "{\"component_appid\":\"" + COMPONENT_APPID + "\"}";
                HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" + component_access_token);
                post.setHeader("Content-Type", "application/json");
                post.setEntity(new StringEntity(parame));

                client = HttpClients.createDefault();
                response = client.execute(post);
                if(response != null && response.getEntity() != null){
                    JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
                    return result.getString("pre_auth_code");
                }
            }else{
                System.out.println("獲取 component_access_token 異常");
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 使用授權碼換取公衆號的授權信息
     * @return  授權方令牌(在授權的公衆號具備API權限時,纔有此返回值)
     */
    public String getAuthorizerAccessToken(String auth_code){
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            String component_access_token = getAccessToken();
            //使用授權碼換取公衆號的授權信息
            String data = "{\"component_appid\":\"" + COMPONENT_APPID + "\",\"authorization_code\":\"" + auth_code + "\"}";
            HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" + component_access_token);
            post.setHeader("Content-Type","application/json");
            post.setEntity(new StringEntity(data));

            client = HttpClients.createDefault();
            response = client.execute(post);

            if(response != null && response.getEntity() != null){
                //響應信息
                /*{"authorization_info": {
                        "authorizer_appid": "wxf8b4f85f3a794e77",
                        "authorizer_access_token": "QXjUqNqfYVH0yBE1iI_7vuN_9gQbpjfK7hYwJ3P7xOa88a89-Aga5x1NMYJyB8G2yKt1KCl0nPC3W9GJzw0Zzq_dBxc8pxIGUNi_bFes0qM",
                        "expires_in": 7200,
                        "authorizer_refresh_token": "dTo-YCXPL4llX-u1W1pPpnp8Hgm4wpJtlR6iV0doKdY",
                        "func_info": [
                            {"funcscope_category": {"id": 1}},
                            {"funcscope_category": {"id": 2}},
                            {"funcscope_category": {"id": 3}}
                        ]}
                  }
                */
                JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
                JSONObject authorization_info = result.getJSONObject("authorization_info");
                String so_release_access_token = authorization_info.getString("authorizer_access_token");//授權access_token
                Long expires_in = authorization_info.getLong("expires_in");//有效期
                RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
                redisUtil.set("so_release_access_token", so_release_access_token, expires_in);
                return so_release_access_token;
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 獲取授權的Appid
     */
    String getAuthorizerAppidFromXml(String xml) {
        Document doc;
        try {
            doc = DocumentHelper.parseText(xml);
            Element rootElt = doc.getRootElement();
            String toUserName = rootElt.elementText("ToUserName");
            return toUserName;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }


//----------------------------------------------------------------以上是微信公衆號全網發佈檢測授權----------------------------------------------------------------------------


    /**
     * 保存Ticket
     */
    public void processAuthorizationEvent(String xml){
        Document doc;
        try {
            doc = DocumentHelper.parseText(xml);
            Element rootElt = doc.getRootElement();
            String ticket = rootElt.elementText("ComponentVerifyTicket");
            System.out.println("*****************************************ticket=" + ticket);
            if(ticket != null && !"".equals(ticket)) {
                RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);
                redisUtil.set("component_verify_ticket", ticket.substring(ticket.indexOf("@@@") + 3));
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    /**
     * 判斷是否加密
     */
    public static boolean checkSignature(String token,String signature,String timestamp,String nonce){
        System.out.println("###token:"+token+";signature:"+signature+";timestamp:"+timestamp+"nonce:"+nonce);
        boolean flag = false;
        if(signature!=null && !signature.equals("") && timestamp!=null && !timestamp.equals("") && nonce!=null && !nonce.equals("")){
            String sha1 = "";
            String[] ss = new String[] { token, timestamp, nonce };
            Arrays.sort(ss);
            for (String s : ss) {
                sha1 += s;
            }

            sha1 = AddSHA1.SHA1(sha1);

            if (sha1.equals(signature)){
                flag = true;
            }
        }
        return flag;
    }


    /**
     * 工具類:回覆微信服務器"文本消息"
     */
    public void output(HttpServletResponse response,String returnvaleue){
        try {
            PrintWriter pw = response.getWriter();
            pw.write(returnvaleue);
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//-------------------------------------------------------------------以上是通用工具方法---------------------------------------------------------------------------------------
}

 

加密解密(此部分是我從微信官網下載,修改了其中一個解密的作用域):

package jc.wx.networkreleasemonitoring.networkreleasemonitoring.utils;
/**
 * 對公衆平臺發送給公衆賬號的消息加解密示例代碼.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

/**
 * 針對org.apache.commons.codec.binary.Base64,
 * 需要導入架包commons-codec-1.9(或commons-codec-1.8等其他版本)
 * 官方下載地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi
 */

import java.io.StringReader;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * 提供接收和推送給公衆平臺消息的加解密接口(UTF8編碼的字符串).
 * <ol>
 * 	<li>第三方回覆加密消息給公衆平臺</li>
 * 	<li>第三方收到公衆平臺發送的消息,驗證消息的安全性,並對消息進行解密。</li>
 * </ol>
 * 說明:異常java.security.InvalidKeyException:illegal Key Size的解決方案
 * <ol>
 * 	<li>在官方網站下載JCE無限制權限策略文件(JDK7的下載地址:
 *      http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</li>
 * 	<li>下載後解壓,可以看到local_policy.jar和US_export_policy.jar以及readme.txt</li>
 * 	<li>如果安裝了JRE,將兩個jar文件放到%JRE_HOME%\lib\security目錄下覆蓋原來的文件</li>
 * 	<li>如果安裝了JDK,將兩個jar文件放到%JDK_HOME%\jre\lib\security目錄下覆蓋原來文件</li>
 * </ol>
 */
public class WXBizMsgCrypt {
    static Charset CHARSET = Charset.forName("utf-8");
    Base64 base64 = new Base64();
    byte[] aesKey;
    String token;
    String appId;

    /**
     * 構造函數
     * @param token 公衆平臺上,開發者設置的token
     * @param encodingAesKey 公衆平臺上,開發者設置的EncodingAESKey
     * @param appId 公衆平臺appid
     *
     * @throws AesException 執行失敗,請查看該異常的錯誤碼和具體的錯誤信息
     */
    public WXBizMsgCrypt(String token, String encodingAesKey, String appId) throws AesException {
        if (encodingAesKey.length() != 43) {
            throw new AesException(AesException.IllegalAesKey);
        }

        this.token = token;
        this.appId = appId;
        aesKey = Base64.decodeBase64(encodingAesKey + "=");
    }

    // 生成4個字節的網絡字節序
    byte[] getNetworkBytesOrder(int sourceNumber) {
        byte[] orderBytes = new byte[4];
        orderBytes[3] = (byte) (sourceNumber & 0xFF);
        orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
        orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
        orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
        return orderBytes;
    }

    // 還原4個字節的網絡字節序
    int recoverNetworkBytesOrder(byte[] orderBytes) {
        int sourceNumber = 0;
        for (int i = 0; i < 4; i++) {
            sourceNumber <<= 8;
            sourceNumber |= orderBytes[i] & 0xff;
        }
        return sourceNumber;
    }

    // 隨機生成16位字符串
    String getRandomStr() {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 對明文進行加密.
     *
     * @param text 需要加密的明文
     * @return 加密後base64編碼的字符串
     * @throws AesException aes加密失敗
     */
    String encrypt(String randomStr, String text) throws AesException {
        ByteGroup byteCollector = new ByteGroup();
        byte[] randomStrBytes = randomStr.getBytes(CHARSET);
        byte[] textBytes = text.getBytes(CHARSET);
        byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
        byte[] appidBytes = appId.getBytes(CHARSET);

        // randomStr + networkBytesOrder + text + appid
        byteCollector.addBytes(randomStrBytes);
        byteCollector.addBytes(networkBytesOrder);
        byteCollector.addBytes(textBytes);
        byteCollector.addBytes(appidBytes);

        // ... + pad: 使用自定義的填充方式對明文進行補位填充
        byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
        byteCollector.addBytes(padBytes);

        // 獲得最終的字節流, 未加密
        byte[] unencrypted = byteCollector.toBytes();

        try {
            // 設置加密模式爲AES的CBC模式
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);

            // 加密
            byte[] encrypted = cipher.doFinal(unencrypted);

            // 使用BASE64對加密後的字符串進行編碼
            String base64Encrypted = base64.encodeToString(encrypted);

            return base64Encrypted;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.EncryptAESError);
        }
    }

    /**
     * 對密文進行解密.
     *
     * @param text 需要解密的密文
     * @return 解密得到的明文
     * @throws AesException aes解密失敗
     */
    public String decrypt(String text) throws AesException {
        byte[] original;
        try {
            // 設置解密模式爲AES的CBC模式
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
            IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
            cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);

            // 使用BASE64對密文進行解碼
            byte[] encrypted = Base64.decodeBase64(text);

            // 解密
            original = cipher.doFinal(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.DecryptAESError);
        }

        String xmlContent, from_appid;
        try {
            // 去除補位字符
            byte[] bytes = PKCS7Encoder.decode(original);

            // 分離16位隨機字符串,網絡字節序和AppId
            byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);

            int xmlLength = recoverNetworkBytesOrder(networkOrder);

            xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
            from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
                    CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.IllegalBuffer);
        }

        // appid不相同的情況
        if (!from_appid.equals(appId)) {
            throw new AesException(AesException.ValidateAppidError);
        }
        return xmlContent;

    }

    /**
     * 將公衆平臺回覆用戶的消息加密打包.
     * <ol>
     * 	<li>對要發送的消息進行AES-CBC加密</li>
     * 	<li>生成安全簽名</li>
     * 	<li>將消息密文和安全簽名打包成xml格式</li>
     * </ol>
     *
     * @param replyMsg 公衆平臺待回覆用戶的消息,xml格式的字符串
     * @param timeStamp 時間戳,可以自己生成,也可以用URL參數的timestamp
     * @param nonce 隨機串,可以自己生成,也可以用URL參數的nonce
     *
     * @return 加密後的可以直接回複用戶的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
     * @throws AesException 執行失敗,請查看該異常的錯誤碼和具體的錯誤信息
     */
    public String encryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {
        // 加密
        String encrypt = encrypt(getRandomStr(), replyMsg);

        // 生成安全簽名
        if (timeStamp == "") {
            timeStamp = Long.toString(System.currentTimeMillis());
        }

        String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);

        // System.out.println("發送給平臺的簽名是: " + signature[1].toString());
        // 生成發送的xml
        String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
        return result;
    }

    /**
     * 檢驗消息的真實性,並且獲取解密後的明文.
     * <ol>
     * 	<li>利用收到的密文生成安全簽名,進行簽名驗證</li>
     * 	<li>若驗證通過,則提取xml中的加密消息</li>
     * 	<li>對消息進行解密</li>
     * </ol>
     *
     * @param msgSignature 簽名串,對應URL參數的msg_signature
     * @param timeStamp 時間戳,對應URL參數的timestamp
     * @param nonce 隨機串,對應URL參數的nonce
     * @param postData 密文,對應POST請求的數據
     *
     * @return 解密後的原文
     * @throws AesException 執行失敗,請查看該異常的錯誤碼和具體的錯誤信息
     */
    public String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData)
            throws AesException {

        // 密鑰,公衆賬號的app secret
        // 提取密文
        Object[] encrypt = XMLParse.extract(postData);

        // 驗證安全簽名
        String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString());

        // 和URL中的簽名比較是否相等
        // System.out.println("第三方收到URL中的簽名:" + msg_sign);
        // System.out.println("第三方校驗簽名:" + signature);
        if (!signature.equals(msgSignature)) {
            throw new AesException(AesException.ValidateSignatureError);
        }

        // 解密
        String result = decrypt(encrypt[1].toString());
        return result;
    }

    /**
     * 驗證URL
     * @param msgSignature 簽名串,對應URL參數的msg_signature
     * @param timeStamp 時間戳,對應URL參數的timestamp
     * @param nonce 隨機串,對應URL參數的nonce
     * @param echoStr 隨機串,對應URL參數的echostr
     *
     * @return 解密之後的echostr
     * @throws AesException 執行失敗,請查看該異常的錯誤碼和具體的錯誤信息
     */
    public String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr)
            throws AesException {
        String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr);

        if (!signature.equals(msgSignature)) {
            throw new AesException(AesException.ValidateSignatureError);
        }

        String result = decrypt(echoStr);
        return result;
    }

}






class ByteGroup {
    ArrayList<Byte> byteContainer = new ArrayList<Byte>();

    public byte[] toBytes() {
        byte[] bytes = new byte[byteContainer.size()];
        for (int i = 0; i < byteContainer.size(); i++) {
            bytes[i] = byteContainer.get(i);
        }
        return bytes;
    }

    public ByteGroup addBytes(byte[] bytes) {
        for (byte b : bytes) {
            byteContainer.add(b);
        }
        return this;
    }

    public int size() {
        return byteContainer.size();
    }
}









/**
 * SHA1 class
 *
 * 計算公衆平臺的消息簽名接口.
 */
class SHA1 {

    /**
     * 用SHA1算法生成安全簽名
     * @param token 票據
     * @param timestamp 時間戳
     * @param nonce 隨機字符串
     * @param encrypt 密文
     * @return 安全簽名
     * @throws AesException
     */
    public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException
    {
        try {
            String[] array = new String[] { token, timestamp, nonce, encrypt };
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 4; 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);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ComputeSignatureError);
        }
    }
}






/**
 * XMLParse class
 *
 * 提供提取消息格式中的密文及生成回覆消息格式的接口.
 */
class XMLParse {

    /**
     * 提取出xml數據包中的加密消息
     * @param xmltext 待提取的xml字符串
     * @return 提取出的加密消息字符串
     * @throws AesException
     */
    public static Object[] extract(String xmltext) throws AesException     {
        Object[] result = new Object[3];
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
            dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            dbf.setXIncludeAware(false);
            dbf.setExpandEntityReferences(false);
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(xmltext);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            NodeList nodelist1 = root.getElementsByTagName("Encrypt");
            NodeList nodelist2 = root.getElementsByTagName("ToUserName");
            result[0] = 0;
            result[1] = nodelist1.item(0).getTextContent();
            result[2] = nodelist2.item(0).getTextContent();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ParseXmlError);
        }
    }

    /**
     * 生成xml消息
     * @param encrypt 加密後的消息密文
     * @param signature 安全簽名
     * @param timestamp 時間戳
     * @param nonce 隨機字符串
     * @return 生成的xml字符串
     */
    public static String generate(String encrypt, String signature, String timestamp, String nonce) {

        String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
                + "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
                + "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
        return String.format(format, encrypt, signature, timestamp, nonce);

    }
}




/**
 * 提供基於PKCS7算法的加解密接口.
 */
class PKCS7Encoder {
    static Charset CHARSET = Charset.forName("utf-8");
    static int BLOCK_SIZE = 32;

    /**
     * 獲得對明文進行補位填充的字節.
     *
     * @param count 需要進行填充補位操作的明文字節個數
     * @return 補齊用的字節數組
     */
    static byte[] encode(int count) {
        // 計算需要填充的位數
        int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
        if (amountToPad == 0) {
            amountToPad = BLOCK_SIZE;
        }
        // 獲得補位所用的字符
        char padChr = chr(amountToPad);
        String tmp = new String();
        for (int index = 0; index < amountToPad; index++) {
            tmp += padChr;
        }
        return tmp.getBytes(CHARSET);
    }

    /**
     * 刪除解密後明文的補位字符
     *
     * @param decrypted 解密後的明文
     * @return 刪除補位字符後的明文
     */
    static byte[] decode(byte[] decrypted) {
        int pad = (int) decrypted[decrypted.length - 1];
        if (pad < 1 || pad > 32) {
            pad = 0;
        }
        return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
    }

    /**
     * 將數字轉化成ASCII碼對應的字符,用於對明文進行補碼
     *
     * @param a 需要轉化的數字
     * @return 轉化得到的字符
     */
    static char chr(int a) {
        byte target = (byte) (a & 0xFF);
        return (char) target;
    }

}
package jc.wx.networkreleasemonitoring.networkreleasemonitoring.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class AddSHA1 {
    public static String SHA1(String inStr) {
        MessageDigest md = null;
        String outStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");     //選擇SHA-1,也可以選擇MD5
            byte[] digest = md.digest(inStr.getBytes());       //返回的是byet[],要轉化爲String存儲比較方便
            outStr = bytetoString(digest);
        }
        catch (NoSuchAlgorithmException nsae) {
            nsae.printStackTrace();
        }
        return outStr;
    }


    public static String bytetoString(byte[] digest) {
        String str = "";
        String tempStr = "";

        for (int i = 0; i < digest.length; i++) {
            tempStr = (Integer.toHexString(digest[i] & 0xff));
            if (tempStr.length() == 1) {
                str = str + "0" + tempStr;
            }
            else {
                str = str + tempStr;
            }
        }
        return str.toLowerCase();
    }
}

 

package jc.wx.networkreleasemonitoring.networkreleasemonitoring.utils;

@SuppressWarnings("serial")
public class AesException extends Exception {

    public final static int OK = 0;
    public final static int ValidateSignatureError = -40001;
    public final static int ParseXmlError = -40002;
    public final static int ComputeSignatureError = -40003;
    public final static int IllegalAesKey = -40004;
    public final static int ValidateAppidError = -40005;
    public final static int EncryptAESError = -40006;
    public final static int DecryptAESError = -40007;
    public final static int IllegalBuffer = -40008;
    //public final static int EncodeBase64Error = -40009;
    //public final static int DecodeBase64Error = -40010;
    //public final static int GenReturnXmlError = -40011;

    private int code;

    private static String getMessage(int code) {
        switch (code) {
            case ValidateSignatureError:
                return "簽名驗證錯誤";
            case ParseXmlError:
                return "xml解析失敗";
            case ComputeSignatureError:
                return "sha加密生成簽名失敗";
            case IllegalAesKey:
                return "SymmetricKey非法";
            case ValidateAppidError:
                return "appid校驗失敗";
            case EncryptAESError:
                return "aes加密失敗";
            case DecryptAESError:
                return "aes解密失敗";
            case IllegalBuffer:
                return "解密後得到的buffer非法";
//		case EncodeBase64Error:
//			return "base64加密錯誤";
//		case DecodeBase64Error:
//			return "base64解密錯誤";
//		case GenReturnXmlError:
//			return "xml生成失敗";
            default:
                return null; // cannot be
        }
    }

    public int getCode() {
        return code;
    }

    AesException(int code) {
        super(getMessage(code));
        this.code = code;
    }

}

 

xml轉map:

package jc.wx.networkreleasemonitoring.networkreleasemonitoring.utils;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 處理xml
 */
public class XmlUtil {
    /**
     * xml 轉 map
     * @param strXML    xml
     * @return
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            System.out.println("無效的XML,不能轉換爲MAP。錯誤消息:" + ex.getMessage() + "。XML內容:" + strXML);
        }
        return null;
    }
}

最後祝大家好運

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章