WXBizMsgCrypt.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml;
  6. using System.Collections;
  7. //using System.Web;
  8. using System.Security.Cryptography;
  9. //-40001 : 签名验证错误
  10. //-40002 : xml解析失败
  11. //-40003 : sha加密生成签名失败
  12. //-40004 : AESKey 非法
  13. //-40005 : corpid 校验错误
  14. //-40006 : AES 加密失败
  15. //-40007 : AES 解密失败
  16. //-40008 : 解密后得到的buffer非法
  17. //-40009 : base64加密异常
  18. //-40010 : base64解密异常
  19. namespace Tencent
  20. {
  21. public class WXBizMsgCrypt
  22. {
  23. string m_sToken;
  24. string m_sEncodingAESKey;
  25. string m_sReceiveId;
  26. enum WXBizMsgCryptErrorCode
  27. {
  28. WXBizMsgCrypt_OK = 0,
  29. WXBizMsgCrypt_ValidateSignature_Error = -40001,
  30. WXBizMsgCrypt_ParseXml_Error = -40002,
  31. WXBizMsgCrypt_ComputeSignature_Error = -40003,
  32. WXBizMsgCrypt_IllegalAesKey = -40004,
  33. WXBizMsgCrypt_ValidateCorpid_Error = -40005,
  34. WXBizMsgCrypt_EncryptAES_Error = -40006,
  35. WXBizMsgCrypt_DecryptAES_Error = -40007,
  36. WXBizMsgCrypt_IllegalBuffer = -40008,
  37. WXBizMsgCrypt_EncodeBase64_Error = -40009,
  38. WXBizMsgCrypt_DecodeBase64_Error = -40010
  39. };
  40. //构造函数
  41. // @param sToken: 企业微信后台,开发者设置的Token
  42. // @param sEncodingAESKey: 企业微信后台,开发者设置的EncodingAESKey
  43. // @param sReceiveId: 不同场景含义不同,详见文档说明
  44. public WXBizMsgCrypt(string sToken, string sEncodingAESKey, string sReceiveId)
  45. {
  46. m_sToken = sToken;
  47. m_sReceiveId = sReceiveId;
  48. m_sEncodingAESKey = sEncodingAESKey;
  49. }
  50. //验证URL
  51. // @param sMsgSignature: 签名串,对应URL参数的msg_signature
  52. // @param sTimeStamp: 时间戳,对应URL参数的timestamp
  53. // @param sNonce: 随机串,对应URL参数的nonce
  54. // @param sEchoStr: 随机串,对应URL参数的echostr
  55. // @param sReplyEchoStr: 解密之后的echostr,当return返回0时有效
  56. // @return:成功0,失败返回对应的错误码
  57. public int VerifyURL(string sMsgSignature, string sTimeStamp, string sNonce, string sEchoStr, ref string sReplyEchoStr)
  58. {
  59. int ret = 0;
  60. if (m_sEncodingAESKey.Length!=43)
  61. {
  62. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
  63. }
  64. ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEchoStr, sMsgSignature);
  65. if (0 != ret)
  66. {
  67. return ret;
  68. }
  69. sReplyEchoStr = "";
  70. string cpid = "";
  71. try
  72. {
  73. sReplyEchoStr = Cryptography.AES_decrypt(sEchoStr, m_sEncodingAESKey, ref cpid); //m_sReceiveId);
  74. }
  75. catch (Exception)
  76. {
  77. sReplyEchoStr = "";
  78. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error;
  79. }
  80. if (cpid != m_sReceiveId)
  81. {
  82. sReplyEchoStr = "";
  83. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateCorpid_Error;
  84. }
  85. return 0;
  86. }
  87. // 检验消息的真实性,并且获取解密后的明文
  88. // @param sMsgSignature: 签名串,对应URL参数的msg_signature
  89. // @param sTimeStamp: 时间戳,对应URL参数的timestamp
  90. // @param sNonce: 随机串,对应URL参数的nonce
  91. // @param sPostData: 密文,对应POST请求的数据
  92. // @param sMsg: 解密后的原文,当return返回0时有效
  93. // @return: 成功0,失败返回对应的错误码
  94. public int DecryptMsg(string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, ref string sMsg)
  95. {
  96. if (m_sEncodingAESKey.Length!=43)
  97. {
  98. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
  99. }
  100. XmlDocument doc = new XmlDocument();
  101. XmlNode root;
  102. string sEncryptMsg;
  103. try
  104. {
  105. doc.LoadXml(sPostData);
  106. root = doc.FirstChild;
  107. sEncryptMsg = root["Encrypt"].InnerText;
  108. }
  109. catch (Exception)
  110. {
  111. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ParseXml_Error;
  112. }
  113. //verify signature
  114. int ret = 0;
  115. ret = VerifySignature(m_sToken, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature);
  116. if (ret != 0)
  117. return ret;
  118. //decrypt
  119. string cpid = "";
  120. try
  121. {
  122. sMsg = Cryptography.AES_decrypt(sEncryptMsg, m_sEncodingAESKey, ref cpid);
  123. }
  124. catch (FormatException)
  125. {
  126. sMsg = "";
  127. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecodeBase64_Error;
  128. }
  129. catch (Exception)
  130. {
  131. sMsg = "";
  132. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_DecryptAES_Error;
  133. }
  134. if (cpid != m_sReceiveId)
  135. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateCorpid_Error;
  136. return 0;
  137. }
  138. //将企业号回复用户的消息加密打包
  139. // @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串
  140. // @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp
  141. // @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce
  142. // @param sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
  143. // 当return返回0时有效
  144. // return:成功0,失败返回对应的错误码
  145. public int EncryptMsg(string sReplyMsg, string sTimeStamp, string sNonce, ref string sEncryptMsg)
  146. {
  147. if (m_sEncodingAESKey.Length!=43)
  148. {
  149. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_IllegalAesKey;
  150. }
  151. string raw = "";
  152. try
  153. {
  154. raw = Cryptography.AES_encrypt(sReplyMsg, m_sEncodingAESKey, m_sReceiveId);
  155. }
  156. catch (Exception)
  157. {
  158. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_EncryptAES_Error;
  159. }
  160. string MsgSigature = "";
  161. int ret = 0;
  162. ret = GenarateSinature(m_sToken, sTimeStamp, sNonce, raw, ref MsgSigature);
  163. if (0 != ret)
  164. return ret;
  165. sEncryptMsg = "";
  166. string EncryptLabelHead = "<Encrypt><![CDATA[";
  167. string EncryptLabelTail = "]]></Encrypt>";
  168. string MsgSigLabelHead = "<MsgSignature><![CDATA[";
  169. string MsgSigLabelTail = "]]></MsgSignature>";
  170. string TimeStampLabelHead = "<TimeStamp><![CDATA[";
  171. string TimeStampLabelTail = "]]></TimeStamp>";
  172. string NonceLabelHead = "<Nonce><![CDATA[";
  173. string NonceLabelTail = "]]></Nonce>";
  174. sEncryptMsg = sEncryptMsg + "<xml>" + EncryptLabelHead + raw + EncryptLabelTail;
  175. sEncryptMsg = sEncryptMsg + MsgSigLabelHead + MsgSigature + MsgSigLabelTail;
  176. sEncryptMsg = sEncryptMsg + TimeStampLabelHead + sTimeStamp + TimeStampLabelTail;
  177. sEncryptMsg = sEncryptMsg + NonceLabelHead + sNonce + NonceLabelTail;
  178. sEncryptMsg += "</xml>";
  179. return 0;
  180. }
  181. public class DictionarySort : System.Collections.IComparer
  182. {
  183. public int Compare(object oLeft, object oRight)
  184. {
  185. string sLeft = oLeft as string;
  186. string sRight = oRight as string;
  187. int iLeftLength = sLeft.Length;
  188. int iRightLength = sRight.Length;
  189. int index = 0;
  190. while (index < iLeftLength && index < iRightLength)
  191. {
  192. if (sLeft[index] < sRight[index])
  193. return -1;
  194. else if (sLeft[index] > sRight[index])
  195. return 1;
  196. else
  197. index++;
  198. }
  199. return iLeftLength - iRightLength;
  200. }
  201. }
  202. //Verify Signature
  203. private static int VerifySignature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt, string sSigture)
  204. {
  205. string hash = "";
  206. int ret = 0;
  207. ret = GenarateSinature(sToken, sTimeStamp, sNonce, sMsgEncrypt, ref hash);
  208. if (ret != 0)
  209. return ret;
  210. if (hash == sSigture)
  211. return 0;
  212. else
  213. {
  214. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ValidateSignature_Error;
  215. }
  216. }
  217. public static int GenarateSinature(string sToken, string sTimeStamp, string sNonce, string sMsgEncrypt ,ref string sMsgSignature)
  218. {
  219. ArrayList AL = new ArrayList();
  220. AL.Add(sToken);
  221. AL.Add(sTimeStamp);
  222. AL.Add(sNonce);
  223. AL.Add(sMsgEncrypt);
  224. AL.Sort(new DictionarySort());
  225. string raw = "";
  226. for (int i = 0; i < AL.Count; ++i)
  227. {
  228. raw += AL[i];
  229. }
  230. SHA1 sha;
  231. ASCIIEncoding enc;
  232. string hash = "";
  233. try
  234. {
  235. sha = new SHA1CryptoServiceProvider();
  236. enc = new ASCIIEncoding();
  237. byte[] dataToHash = enc.GetBytes(raw);
  238. byte[] dataHashed = sha.ComputeHash(dataToHash);
  239. hash = BitConverter.ToString(dataHashed).Replace("-", "");
  240. hash = hash.ToLower();
  241. }
  242. catch (Exception)
  243. {
  244. return (int)WXBizMsgCryptErrorCode.WXBizMsgCrypt_ComputeSignature_Error;
  245. }
  246. sMsgSignature = hash;
  247. return 0;
  248. }
  249. }
  250. }