【詳細、開箱即用】.NET企業微信回撥配置(資料回撥URL和指令回撥URL驗證)

追逐時光者發表於2021-09-05

前言:

  前段時間因為公司業務需求,需要將微信小程式與企業微信對接通,也就是把小程式繫結到對應的企業微信賬號下,在該企業微信的使用者可以將該小程式繫結到工作臺中,然後可以在工作臺中開啟該小程式並授權。不過將微信小程式與企業微信對接通需要後臺去做資料回撥URL和指令回撥URL驗證,因為第一次接觸這個然後企業微信文件寫的也不是很詳細,並且在全網沒有找到一篇.NET相關企業微信回撥配置驗證有用的文章,所以這裡把自己的配置詳細過程分享出來,希望能夠幫助更多的同學。

企業微信回撥配置相關文件

回撥配置:

主要講的是回撥配置的一些驗證流程和請求介面。

https://work.weixin.qq.com/api/doc/90000/90135/90930

C#解密類庫:

https://open.work.weixin.qq.com/wwopen/downloadfile/csharp.zip

企業微信回撥配置驗證完整流程

注意:配置回撥服務時,需要能同時支援HttpGet以及HttpPost兩種能力,注意介面一定要是https的安全域名地址。

  • HttpGet介面用於驗證資料回撥URL有效性
  • HttpPost介面用於驗證指令回撥URL有效性

所以我們可以只定義一個介面,通過企業微信請求過來的型別進行不同回撥URL的有效性驗證。

處理企業號的資訊介面:

public class EnterpriseWechatCallbackController : Controller
{

    //企業微信後臺開發者設定的token, corpID, EncodingAESKey
    private readonly string sToken = "追逐時光者";//企業微信後臺,開發者設定的Token
    private readonly string sCorpID = "追逐時光者";//企業號corpid是企業號的專屬編號(CorpID)[不同場景含義不同,詳見文件說明(ToUserName:企業微信的CorpID,當為第三方應用回撥事件時,CorpID的內容為suiteid)]
    private readonly string sEncodingAESKey = "追逐時光者";//企業微信後臺,開發者設定的EncodingAESKey


    /// <summary>
    /// 處理企業號的資訊
    /// get:資料回撥URL驗證;
    /// post:指令回撥URL驗證;
    /// </summary>
    public ActionResult EtWechatCommunication()
    {
        string httpMethod = Request.HttpMethod.ToUpper();

        if (httpMethod == "POST")
        {
            //獲取請求中的xml資料
            string postString = GetXMLParameters(Request);

            string responseContent = "響應失敗,未獲取到xml中的請求引數";
            if (!string.IsNullOrEmpty(postString))
            {
                //指令響應回撥
                responseContent = CommandCallback(Request, postString);
            }

            return Content(responseContent);
        }
        else
        {
            return EtWachatCheckVerifyURL();
        }
    }


    /// <summary>
    /// 資料回撥URL驗證
    /// </summary>
    /// <returns></returns>
    public ActionResult EtWachatCheckVerifyURL()
    {
        string signature = Request.QueryString["msg_signature"];//微信加密簽名,msg_signature結合了企業填寫的token、請求中的timestamp、nonce引數、加密的訊息體
        string timestamp = Request.QueryString["timestamp"];//時間戳
        string nonce = Request.QueryString["nonce"];//隨機數
        string httpMethod = Request.HttpMethod.ToUpper();

        if (httpMethod == "GET")//驗證回撥URL(注意:企業回撥的url-該url不做任何的業務邏輯,僅僅微信檢視是否可以調通)
        {
            try
            {
                //在1秒內響應GET請求,響應內容為上一步得到的明文訊息內容decryptEchoString(不能加引號,不能帶bom頭,不能帶換行符)
                string echostr = Request.QueryString["echostr"];//加密的隨機字串,以msg_encrypt格式提供。需要解密並返回echostr明文,解密後有random、msg_len、msg、$CorpID四個欄位,其中msg即為echostr明文

                if (!IsNullOrWhiteSpace(signature) && !IsNullOrWhiteSpace(timestamp) && !IsNullOrWhiteSpace(nonce) && !IsNullOrWhiteSpace(echostr))
                {
                    string decryptEchoString = null;
                    if (CheckVerifyURL(sToken, signature, timestamp, nonce, sCorpID, sEncodingAESKey, echostr, ref decryptEchoString))
                    {
                        if (!string.IsNullOrEmpty(decryptEchoString))
                        {
                            //必須要返回解密之後的明文
                            return Content(decryptEchoString);
                        }
                    }
                }
                else
                {
                    return Content("fail");
                }
            }
            catch (Exception ex)
            {
                return Content("fail");
            }
        }

        return Content("fail");
    }

    /// <summary>
    /// 驗證URL有效性
    /// </summary>
    /// <param name="token">企業微信後臺,開發者設定的Token</param>
    /// <param name="signature">簽名串,對應URL引數的msg_signature</param>
    /// <param name="timestamp">時間戳</param>
    /// <param name="nonce">隨機數</param>
    /// <param name="corpId">ToUserName為企業號的CorpID</param>
    /// <param name="encodingAESKey">企業微信後臺,開發者設定的EncodingAESKey</param>
    /// <param name="echostr">隨機串,對應URL引數的echostr</param>
    /// <param name="retEchostr">解密之後的echostr,當return返回0時有效</param>
    /// <returns></returns>
    private bool CheckVerifyURL(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr)
    {
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId);

        int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr);

        if (result != 0)
        {
            return false;//FAIL
        }

        //result==0表示驗證成功、retEchostr參數列示明文
        //使用者需要將retEchostr作為get請求的返回引數、返回給企業微訊號
        return true;
    }

    /// <summary>
    /// 指令響應回撥
    /// </summary>
    /// <param name="Request"></param>
    /// <param name="postString">post請求的xml引數</param>
    /// <returns></returns>
    private string CommandCallback(HttpRequestBase Request, string postString)
    {
        string signature = Request.QueryString["msg_signature"];//微信加密簽名,msg_signature結合了企業填寫的token、請求中的timestamp、nonce引數、加密的訊息體
        string timestamp = Request.QueryString["timestamp"];//時間戳
        string nonce = Request.QueryString["nonce"];//隨機數                             
        var xmlDoc = XDocument.Parse(postString);//xml資料轉化

        try
        {
            //https://work.weixin.qq.com/api/doc/90001/90143/90613
            //在發生授權、通訊錄變更、ticket變化等事件時,企業微信伺服器會嚮應用的“指令回撥URL”推送相應的事件訊息。
            //訊息結構體將使用建立應用時的EncodingAESKey進行加密(特別注意, 在第三方回撥事件中使用加解密演算法,receiveid的內容為suiteid),請參考接收訊息解析資料包。 本章節的回撥事件,服務商在收到推送後都必須直接返回字串 “success”,若返回值不是 “success”,企業微信會把返回內容當作錯誤資訊。
            if (xmlDoc.Root.Element("Encrypt") != null)
            {
                //將post請求的資料進行xml解析,並將<Encrypt> 標籤的內容進行解密,解密出來的明文即是使用者回覆訊息的明文
                //接收並讀取POST過來的XML檔案流
                string decryptionParame = null;  // 解析之後的明文

                // 注意注意:sCorpID
                // @param sReceiveId: 不同場景含義不同,詳見文件說明([訊息加密時為 CorpId]ToUserName:企業微信的CorpID,當為第三方應用回撥事件時,CorpID的內容為suiteid)

                WXBizMsgCrypt crypt = new WXBizMsgCrypt(sToken, sEncodingAESKey, xmlDoc.Root.Element("ToUserName").Value);
                var result = crypt.DecryptMsg(signature, timestamp, nonce, postString, ref decryptionParame);

                if (result != 0)
                {
                    return "fial";
                }

                //響應應答處理
                return new InstructionCallbackResponse().ReceiveResponse(decryptionParame, timestamp, signature,sToken, sEncodingAESKey, sCorpID);
            }
        }
        catch (Exception ex)
        {
            //LoggerHelper._.Debug("異常:" + ex.Message);
        }

        return "fail";
    }


    /// <summary>
    /// 驗證是否為空
    /// </summary>
    /// <param name="strParame">驗證引數</param>
    /// <returns></returns>
    private bool IsNullOrWhiteSpace(string strParame)
    {
        if (string.IsNullOrWhiteSpace(strParame))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 獲取post請求中的xml引數
    /// </summary>
    /// <returns></returns>
    private string GetXMLParameters(HttpRequestBase Request)
    {
        string replyMsg;
        using (Stream stream = Request.InputStream)
        {
            Byte[] postBytes = new Byte[stream.Length];
            stream.Read(postBytes, 0, (Int32)stream.Length);
            replyMsg = Encoding.UTF8.GetString(postBytes);
        }
        return replyMsg;
    }

}

指令回撥響應應答處理:

    /// <summary>
    /// 指令回撥響應應答處理
    /// </summary>
    public class InstructionCallbackResponse
    {
        /// <summary>
        /// 響應應答處理
        /// </summary>
        /// <param name="sMsg">解密引數</param>
        /// <param name="timestamp">時間戳</param>
        /// <param name="signature">簽名</param>
        /// <param name="sToken">企業微信後臺,開發者設定的Token</param>
        /// <param name="sEncodingAESKey">開發者設定的EncodingAESKey</param>
        /// <param name="sCorpID">業號corpid是企業號的專屬編號(CorpID)</param>
        /// <returns></returns>
        public string ReceiveResponse(string sMsg, string timestamp, string signature, string sToken, string sEncodingAESKey, string sCorpID)
        {
            string responseMessage = "success";//響應內容   
            var xmlDoc = XDocument.Parse(sMsg);//xml資料轉化

            //區分普通訊息與第三方應用授權推送訊息,MsgType有值說明是普通訊息,反之則是第三方應用授權推送訊息
            if (xmlDoc.Root.Element("MsgType") != null)
            {
                var msgType = (ResponseMsgType)Enum.Parse(typeof(ResponseMsgType), xmlDoc.Root.Element("MsgType").Value, true);
                switch (msgType)
                {
                    case ResponseMsgType.Text://文字訊息
                        responseMessage = ResponseMessageText(xmlDoc, timestamp, signature,sToken,sEncodingAESKey,sCorpID);
                        break;
                    case ResponseMsgType.Image:
                        responseMessage = ResponseMessageImage();
                        break;
                    case ResponseMsgType.Voice:
                        responseMessage = ResponseMessageVoice();
                        break;
                    case ResponseMsgType.Video:
                        responseMessage = ResponseMessageVideo();
                        break;
                    case ResponseMsgType.News:
                        responseMessage = ResponseMessageNews();
                        break;
                }
            }
            else if (xmlDoc.Root.Element("InfoType") != null)
            {
                //第三方回撥
                var infoType = (ResponseInfoType)Enum.Parse(typeof(ResponseInfoType), xmlDoc.Root.Element("InfoType").Value, true);

                switch (infoType)
                {
                    case ResponseInfoType.suite_ticket:
                        {
                            //LoggerHelper._.Warn("suite_ticket===>>>>>,進來了,獲取到的SuiteTicket票據為" + xmlDoc.Root.Element("SuiteTicket").Value);
                        }
                        break;
                }
            }
            else
            {
                //其他情況
            }

            // result==0表示解密成功,sMsg表示解密之後的明文xml串
            //伺服器未正確返回響應字串 “success”
            return responseMessage;
        }


        #region 相關事件實現

        /// <summary>
        /// 訊息文字回復
        /// </summary>
        /// <returns></returns>
        public string ResponseMessageText(XDocument xmlDoc, string timestamp, string nonce,string sToken,string sEncodingAESKey,string sCorpID)
        {
            string FromUserName = xmlDoc.Root.Element("FromUserName").Value;
            string ToUserName = xmlDoc.Root.Element("ToUserName").Value;
            string Content = xmlDoc.Root.Element("Content").Value;

            string xml = "<xml>";
            xml += "<ToUserName><![CDATA[" + ToUserName + "]]></ToUserName>";
            xml += "<FromUserName><![CDATA[" + FromUserName + "]]></FromUserName>";
            xml += "<CreateTime>" + GetCurrentTimeUnix() + "</CreateTime>";
            xml += "<MsgType><![CDATA[text]]></MsgType>";
            xml += "<Content><![CDATA[" + Content + "]]></Content>";
            xml += "</xml>";
            //"" + Content + "0";//回覆內容 FuncFlag設定為1的時候,自動星標剛才接收到的訊息,適合活動統計使用
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
            string sEncryptMsg = "";// 加密後的可以直接回複使用者的密文;
            wxcpt.EncryptMsg(xml, timestamp, nonce, ref sEncryptMsg);

            //返回
            return sEncryptMsg;
        }

        /// <summary>
        /// 圖片訊息
        /// </summary>
        /// <returns></returns>

        public string ResponseMessageImage()
        {
            return "success";
        }

        /// <summary>
        /// 語音訊息
        /// </summary>
        /// <returns></returns>
        public string ResponseMessageVoice()
        {
            return "success";
        }

        /// <summary>
        /// 視訊訊息
        /// </summary>
        /// <returns></returns>
        public string ResponseMessageVideo()
        {
            return "success";
        }

        /// <summary>
        /// 圖文訊息
        /// </summary>
        /// <returns></returns>
        public string ResponseMessageNews()
        {
            return "success";
        }

        #endregion

        /// <summary>
        /// 獲取當前時間戳
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentTimeUnix()
        {
            TimeSpan cha = (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)));
            long t = (long)cha.TotalSeconds;
            return t.ToString();
        }
    }

訊息型別列舉(enumType):

第三方應用授權推送訊息型別(ResponseInfoType)

/// <summary>
    /// 第三方應用授權推送訊息型別
    /// </summary>
    public enum ResponseInfoType
    {
        /// <summary>
        /// 推送suite_ticket 企業微信伺服器會定時(每十分鐘)推送ticket。ticket會實時變更,並用於後續介面的呼叫。
        /// </summary>
        suite_ticket =1,

        /// <summary>
        /// 授權成功通知
        /// </summary>
        create_auth = 2,

        /// <summary>
        /// 成員通知事件
        /// </summary>
        change_contact = 3
    }

普通訊息響應型別(ResponseMsgType)

/// <summary>
    /// 普通訊息響應型別
    /// </summary>
    public enum ResponseMsgType
    {
        /// <summary>
        /// 文字訊息
        /// </summary>
        Text = 0,
        /// <summary>
        /// 圖文訊息
        /// </summary>
        News = 1,
        /// <summary>
        /// 圖片訊息
        /// </summary>
        Image = 3,
        /// <summary>
        /// 語音訊息
        /// </summary>
        Voice = 4,
        /// <summary>
        /// 視訊訊息
        /// </summary>
        Video = 5
    }

C#解密類庫

WXBizMsgCrypt

 public class WXBizMsgCrypt
    {
        string m_sToken;
        string m_sEncodingAESKey;
        string m_sReceiveId;

        //-40001 : 簽名驗證錯誤
        //-40002 :  xml解析失敗
        //-40003 :  sha加密生成簽名失敗
        //-40004 :  AESKey 非法
        //-40005 :  corpid 校驗錯誤
        //-40006 :  AES 加密失敗
        //-40007 : AES 解密失敗
        //-40008 : 解密後得到的buffer非法
        //-40009 :  base64加密異常
        //-40010 :  base64解密異常

        enum WXBizMsgCryptErrorCode
        {
            WXBizMsgCrypt_OK = 0,
            WXBizMsgCrypt_ValidateSignature_Error = -40001,
            WXBizMsgCrypt_ParseXml_Error = -40002,
            WXBizMsgCrypt_ComputeSignature_Error = -40003,
            WXBizMsgCrypt_IllegalAesKey = -40004,
            WXBizMsgCrypt_ValidateCorpid_Error = -40005,
            WXBizMsgCrypt_EncryptAES_Error = -40006,
            WXBizMsgCrypt_DecryptAES_Error = -40007,
            WXBizMsgCrypt_IllegalBuffer = -40008,
            WXBizMsgCrypt_EncodeBase64_Error = -40009,
            WXBizMsgCrypt_DecodeBase64_Error = -40010
        };

        //建構函式
        // @param sToken: 企業微信後臺,開發者設定的Token
        // @param sEncodingAESKey: 企業微信後臺,開發者設定的EncodingAESKey
        // @param sReceiveId: 不同場景含義不同,詳見文件說明([訊息加密時為 CorpId]ToUserName:企業微信的CorpID,當為第三方應用回撥事件時,CorpID的內容為suiteid)
        public WXBizMsgCrypt(string sToken, string sEncodingAESKey, string sReceiveId)
        {
            m_sToken = sToken;
            m_sReceiveId = sReceiveId;
            m_sEncodingAESKey = sEncodingAESKey;
        }

        //驗證URL
        // @param sMsgSignature: 簽名串,對應URL引數的msg_signature
        // @param sTimeStamp: 時間戳,對應URL引數的timestamp
        // @param sNonce: 隨機串,對應URL引數的nonce
        // @param sEchoStr: 隨機串,對應URL引數的echostr
        // @param sReplyEchoStr: 解密之後的echostr,當return返回0時有效
        // @return:成功0,失敗返回對應的錯誤碼
        public int VerifyURL(string sMsgSignature, string sTimeStamp, string sNonce, string sEchoStr, ref string sReplyEchoStr)
        {
            int ret = 0;
            if (m_sEncodingAESKey.Length != 43)
            {
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
            }
            ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEchoStr, sMsgSignature);
            if (0 != ret)
            {
                return ret;
            }
            sReplyEchoStr = "";
            string cpid = "";
            try
            {
                sReplyEchoStr = Cryptography.AES_decrypt(sEchoStr, m_sEncodingAESKey, ref cpid); //m_sReceiveId);
            }
            catch (Exception)
            {
                sReplyEchoStr = "";
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error;
            }
            if (cpid != m_sReceiveId)
            {
                sReplyEchoStr = "";
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateCorpid_Error;
            }
            return 0;
        }

        // 檢驗訊息的真實性,並且獲取解密後的明文
        // @param sMsgSignature: 簽名串,對應URL引數的msg_signature
        // @param sTimeStamp: 時間戳,對應URL引數的timestamp
        // @param sNonce: 隨機串,對應URL引數的nonce
        // @param sPostData: 密文,對應POST請求的資料
        // @param sMsg: 解密後的原文,當return返回0時有效
        // @return: 成功0,失敗返回對應的錯誤碼
        public int DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, ref string sMsg)
        {
            if (m_sEncodingAESKey.Length != 43)
            {
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
            }
            XmlDocument doc = new XmlDocument();
            XmlNode root;
            string sEncryptMsg;
            try
            {
                doc.LoadXml(sPostData);
                root = doc.FirstChild;
                sEncryptMsg = root["Encrypt"].InnerText;

                LoggerHelper._.Info("進來解密了,解密密文sEncryptMsg為:" + sEncryptMsg);
            }
            catch (Exception)
            {
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ParseXml_Error;
            }
            //verify signature
            int ret = 0;
            ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature);

            LoggerHelper._.Info("進來解密了,解密結果:" + ret);

            if (ret != 0)
                return ret;
            //decrypt
            string cpid = "";
            try
            {
                sMsg = Cryptography.AES_decrypt(sEncryptMsg, m_sEncodingAESKey, ref cpid);
            }
            catch (FormatException)
            {
                sMsg = "";
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecodeBase64_Error;
            }
            catch (Exception)
            {
                sMsg = "";
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error;
            }
            if (cpid != m_sReceiveId)
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateCorpid_Error;
            return 0;
        }

        //將企業號回覆使用者的訊息加密打包
        // @param sReplyMsg: 企業號待回覆使用者的訊息,xml格式的字串
        // @param sTimeStamp: 時間戳,可以自己生成,也可以用URL引數的timestamp
        // @param sNonce: 隨機串,可以自己生成,也可以用URL引數的nonce
        // @param sEncryptMsg: 加密後的可以直接回複使用者的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字串,當return返回0時有效
        // return:成功0,失敗返回對應的錯誤碼
        public int EncryptMsg(string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg)
        {
            if (m_sEncodingAESKey.Length != 43)
            {
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
            }
            string raw = "";
            try
            {
                raw = Cryptography.AES_encrypt(sReplyMsg, m_sEncodingAESKey, m_sReceiveId);
            }
            catch (Exception)
            {
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_EncryptAES_Error;
            }
            string MsgSigature = "";
            int ret = 0;
            ret = GenarateSinature(m_sToken, sTimeStamp, sNonce, raw, ref MsgSigature);
            if (0 != ret)
                return ret;
            sEncryptMsg = "";

            string EncryptLabelHead = "<Encrypt><![CDATA[";
            string EncryptLabelTail = "]]></Encrypt>";
            string MsgSigLabelHead = "<MsgSignature><![CDATA[";
            string MsgSigLabelTail = "]]></MsgSignature>";
            string TimeStampLabelHead = "<TimeStamp><![CDATA[";
            string TimeStampLabelTail = "]]></TimeStamp>";
            string NonceLabelHead = "<Nonce><![CDATA[";
            string NonceLabelTail = "]]></Nonce>";
            sEncryptMsg = sEncryptMsg + "<xml>" + EncryptLabelHead + raw + EncryptLabelTail;
            sEncryptMsg = sEncryptMsg + MsgSigLabelHead + MsgSigature + MsgSigLabelTail;
            sEncryptMsg = sEncryptMsg + TimeStampLabelHead + sTimeStamp + TimeStampLabelTail;
            sEncryptMsg = sEncryptMsg + NonceLabelHead + sNonce + NonceLabelTail;
            sEncryptMsg += "</xml>";
            return 0;
        }

        public class DictionarySort : System.Collections.IComparer
        {
            public int Compare(object oLeft, object oRight)
            {
                string sLeft = oLeft as string;
                string sRight = oRight as string;
                int iLeftLength = sLeft.Length;
                int iRightLength = sRight.Length;
                int index = 0;
                while (index < iLeftLength && index < iRightLength)
                {
                    if (sLeft[index] < sRight[index])
                        return -1;
                    else if (sLeft[index] > sRight[index])
                        return 1;
                    else
                        index++;
                }
                return iLeftLength - iRightLength;

            }
        }
        //Verify Signature
        private static int VerifySignature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, string sSigture)
        {
            string hash = "";
            int ret = 0;
            ret = GenarateSinature(sToken, sTimeStamp, sNonce, sMsgEncrypt, ref hash);
            if (ret != 0)
                return ret;
            if (hash == sSigture)
                return 0;
            else
            {
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateSignature_Error;
            }
        }

        public static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, ref string sMsgSignature)
        {
            //校驗規則:https://work.weixin.qq.com/api/doc#90000/90139/90968/%E6%B6%88%E6%81%AF%E4%BD%93%E7%AD%BE%E5%90%8D%E6%A0%A1%E9%AA%8C

            ArrayList AL = new ArrayList();
            AL.Add(sToken);
            AL.Add(sTimeStamp);
            AL.Add(sNonce);
            AL.Add(sMsgEncrypt);
            AL.Sort(new DictionarySort());
            string raw = "";
            for (int i = 0; i < AL.Count; ++i)
            {
                raw += AL[i];
            }

            SHA1 sha;
            ASCIIEncoding enc;
            string hash = "";
            try
            {
                sha = new SHA1CryptoServiceProvider();
                enc = new ASCIIEncoding();
                byte[] dataToHash = enc.GetBytes(raw);
                byte[] dataHashed = sha.ComputeHash(dataToHash);
                hash = BitConverter.ToString(dataHashed).Replace("-", "");
                hash = hash.ToLower();
            }
            catch (Exception)
            {
                return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error;
            }
            sMsgSignature = hash;
            return 0;
        }

    }

Cryptography

    public class Cryptography
    {
        public static UInt32 HostToNetworkOrder(UInt32 inval)
        {
            UInt32 outval = 0;
            for (int i = 0; i < 4; i++)
                outval = (outval << 8) + ((inval >> (i * 8)) & 255);
            return outval;
        }

        public static Int32 HostToNetworkOrder(Int32 inval)
        {
            Int32 outval = 0;
            for (int i = 0; i < 4; i++)
                outval = (outval << 8) + ((inval >> (i * 8)) & 255);
            return outval;
        }
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="Input">密文</param>
        /// <param name="EncodingAESKey"></param>
        /// <returns></returns>
        /// 
        public static string AES_decrypt(String Input, string EncodingAESKey, ref string corpid)
        {
            byte[] Key;
            Key = Convert.FromBase64String(EncodingAESKey + "=");
            byte[] Iv = new byte[16];
            Array.Copy(Key, Iv, 16);
            byte[] btmpMsg = AES_decrypt(Input, Iv, Key);

            int len = BitConverter.ToInt32(btmpMsg, 16);
            len = IPAddress.NetworkToHostOrder(len);


            byte[] bMsg = new byte[len];
            byte[] bCorpid = new byte[btmpMsg.Length - 20 - len];
            Array.Copy(btmpMsg, 20, bMsg, 0, len);
            Array.Copy(btmpMsg, 20 + len, bCorpid, 0, btmpMsg.Length - 20 - len);
            string oriMsg = Encoding.UTF8.GetString(bMsg);
            corpid = Encoding.UTF8.GetString(bCorpid);


            return oriMsg;
        }

        public static String AES_encrypt(String Input, string EncodingAESKey, string corpid)
        {
            byte[] Key;
            Key = Convert.FromBase64String(EncodingAESKey + "=");
            byte[] Iv = new byte[16];
            Array.Copy(Key, Iv, 16);
            string Randcode = CreateRandCode(16);
            byte[] bRand = Encoding.UTF8.GetBytes(Randcode);
            byte[] bCorpid = Encoding.UTF8.GetBytes(corpid);
            byte[] btmpMsg = Encoding.UTF8.GetBytes(Input);
            byte[] bMsgLen = BitConverter.GetBytes(HostToNetworkOrder(btmpMsg.Length));
            byte[] bMsg = new byte[bRand.Length + bMsgLen.Length + bCorpid.Length + btmpMsg.Length];

            Array.Copy(bRand, bMsg, bRand.Length);
            Array.Copy(bMsgLen, 0, bMsg, bRand.Length, bMsgLen.Length);
            Array.Copy(btmpMsg, 0, bMsg, bRand.Length + bMsgLen.Length, btmpMsg.Length);
            Array.Copy(bCorpid, 0, bMsg, bRand.Length + bMsgLen.Length + btmpMsg.Length, bCorpid.Length);

            return AES_encrypt(bMsg, Iv, Key);

        }
        private static string CreateRandCode(int codeLen)
        {
            string codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
            if (codeLen == 0)
            {
                codeLen = 16;
            }
            string[] arr = codeSerial.Split(',');
            string code = "";
            int randValue = -1;
            Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
            for (int i = 0; i < codeLen; i++)
            {
                randValue = rand.Next(0, arr.Length - 1);
                code += arr[randValue];
            }
            return code;
        }

        private static String AES_encrypt(String Input, byte[] Iv, byte[] Key)
        {
            //var aes = new RijndaelManaged();
#if NET45
            var aes = new RijndaelManaged();
#else
            var aes = Aes.Create();
#endif
            //祕鑰的大小,以位為單位
            aes.KeySize = 256;
            //支援的塊大小
            aes.BlockSize = 128;
            //填充模式
            aes.Padding = PaddingMode.PKCS7;
            aes.Mode = CipherMode.CBC;
            aes.Key = Key;
            aes.IV = Iv;
            var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
            byte[] xBuff = null;

            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    byte[] xXml = Encoding.UTF8.GetBytes(Input);
                    cs.Write(xXml, 0, xXml.Length);
                }
                xBuff = ms.ToArray();
            }
            String Output = Convert.ToBase64String(xBuff);
            return Output;
        }

        private static String AES_encrypt(byte[] Input, byte[] Iv, byte[] Key)
        {
            //var aes = new RijndaelManaged();
#if NET45
            var aes = new RijndaelManaged();
#else
            var aes = Aes.Create();
#endif
            //祕鑰的大小,以位為單位
            aes.KeySize = 256;
            //支援的塊大小
            aes.BlockSize = 128;
            //填充模式
            //aes.Padding = PaddingMode.PKCS7;
            aes.Padding = PaddingMode.None;
            aes.Mode = CipherMode.CBC;
            aes.Key = Key;
            aes.IV = Iv;
            var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
            byte[] xBuff = null;

            #region 自己進行PKCS7補位,用系統自己帶的不行
            byte[] msg = new byte[Input.Length + 32 - Input.Length % 32];
            Array.Copy(Input, msg, Input.Length);
            byte[] pad = KCS7Encoder(Input.Length);
            Array.Copy(pad, 0, msg, Input.Length, pad.Length);
            #endregion

            #region 註釋的也是一種方法,效果一樣
            //ICryptoTransform transform = aes.CreateEncryptor();
            //byte[] xBuff = transform.TransformFinalBlock(msg, 0, msg.Length);
            #endregion

            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
                {
                    cs.Write(msg, 0, msg.Length);
                }
                xBuff = ms.ToArray();
            }

            String Output = Convert.ToBase64String(xBuff);
            return Output;
        }

        private static byte[] KCS7Encoder(int text_length)
        {
            int block_size = 32;
            // 計算需要填充的位數
            int amount_to_pad = block_size - (text_length % block_size);
            if (amount_to_pad == 0)
            {
                amount_to_pad = block_size;
            }
            // 獲得補位所用的字元
            char pad_chr = chr(amount_to_pad);
            string tmp = "";
            for (int index = 0; index < amount_to_pad; index++)
            {
                tmp += pad_chr;
            }
            return Encoding.UTF8.GetBytes(tmp);
        }
        /**
         * 將數字轉化成ASCII碼對應的字元,用於對明文進行補碼
         * 
         * @param a 需要轉化的數字
         * @return 轉化得到的字元
         */
        static char chr(int a)
        {

            byte target = (byte)(a & 0xFF);
            return (char)target;
        }
        private static byte[] AES_decrypt(String Input, byte[] Iv, byte[] Key)
        {
            //RijndaelManaged aes = new RijndaelManaged();
#if NET45
            var aes = new RijndaelManaged();
#else
            var aes = Aes.Create();
#endif
            aes.KeySize = 256;
            aes.BlockSize = 128;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.None;
            aes.Key = Key;
            aes.IV = Iv;
            var decrypt = aes.CreateDecryptor(aes.Key, aes.IV);
            byte[] xBuff = null;
            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
                {
                    byte[] xXml = Convert.FromBase64String(Input);
                    byte[] msg = new byte[xXml.Length + 32 - xXml.Length % 32];
                    Array.Copy(xXml, msg, xXml.Length);
                    cs.Write(xXml, 0, xXml.Length);
                }
                xBuff = decode2(ms.ToArray());
            }
            return xBuff;
        }
        private static byte[] decode2(byte[] decrypted)
        {
            int pad = (int)decrypted[decrypted.Length - 1];
            if (pad < 1 || pad > 32)
            {
                pad = 0;
            }
            byte[] res = new byte[decrypted.Length - pad];
            Array.Copy(decrypted, 0, res, 0, decrypted.Length - pad);
            return res;
        }
    }

企業微信後臺驗證回撥URL有效性 

 

 

相關文章