微信公众平台第三方平台全网发布 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;
    }
}

最后祝大家好运

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值