CallbackCrypto.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace SiteCore.taoObj
  7. {
  8. using System.Diagnostics.CodeAnalysis;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. namespace WebApi
  12. {
  13. public class CallbackCrypto
  14. {
  15. private readonly byte[] _aesKey;
  16. private readonly string _clientId;
  17. //随机字符串字节长度
  18. private static readonly int RANDOM_LENGTH = 16;
  19. /// <summary>
  20. /// 构造函数
  21. /// </summary>
  22. /// <param name="encodingAesKey">开放平台上,开发者设置的EncodingAESKey</param>
  23. /// <param name="clientId">开放平台上,应用的clientId</param>
  24. /// <exception cref="CallbackCryptoException"></exception>
  25. public CallbackCrypto(string encodingAesKey, string clientId)
  26. {
  27. if (encodingAesKey == null)
  28. {
  29. throw new Exception("加密密钥不能为空");
  30. }
  31. _clientId = clientId;
  32. _aesKey = Convert.FromBase64String(encodingAesKey);
  33. }
  34. /// <summary>
  35. /// 将和开放平台同步的消息体加密,返回加密Map
  36. /// </summary>
  37. /// <param name="plaintext">传递的消息体明文</param>
  38. /// <returns></returns>
  39. public Dictionary<string, string> GetEncryptedMap(string plaintext)
  40. {
  41. return GetEncryptedMap(plaintext, DateTime.Now.Millisecond);
  42. }
  43. /// <summary>
  44. /// 将和开放平台同步的消息体加密,返回加密Map
  45. /// </summary>
  46. /// <param name="plaintext">传递的消息体明文</param>
  47. /// <param name="timestamp">时间戳</param>
  48. /// <returns></returns>
  49. /// <exception cref="CallbackCryptoException"></exception>
  50. public Dictionary<string, string> GetEncryptedMap(string plaintext, long timestamp)
  51. {
  52. if (null == plaintext)
  53. {
  54. throw new Exception("加密明文字符串不能为空");
  55. }
  56. var nonce = Utils.GetRandomStr(RANDOM_LENGTH);
  57. string encrypt = Encrypt(nonce, plaintext);
  58. string signature = GetSignature(timestamp.ToString(), nonce, encrypt);
  59. return new Dictionary<string, string>()
  60. {
  61. ["signature"] = signature,
  62. ["encrypt"] = encrypt,
  63. ["timestamp"] = timestamp.ToString(),
  64. ["nonce"] = nonce
  65. };
  66. }
  67. /// <summary>
  68. /// 密文解密
  69. /// </summary>
  70. /// <param name="msgSignature">签名串</param>
  71. /// <param name="timestamp">时间戳</param>
  72. /// <param name="nonce">随机串</param>
  73. /// <param name="encryptMsg">密文</param>
  74. /// <returns>解密后的原文</returns>
  75. /// <exception cref="CallbackCryptoException"></exception>
  76. public string GetDecryptMsg(string msgSignature, string timestamp, string nonce, string encryptMsg)
  77. {
  78. //校验签名
  79. string signature = GetSignature(timestamp, nonce, encryptMsg);
  80. if (!signature.Equals(msgSignature))
  81. {
  82. throw new Exception("签名不匹配");
  83. }
  84. // 解密
  85. return Decrypt(encryptMsg);
  86. }
  87. /// <summary>
  88. /// 对明文加密
  89. /// </summary>
  90. /// <param name="nonce">随机串</param>
  91. /// <param name="plaintext">需要加密的明文</param>
  92. /// <returns>加密后base64编码的字符串</returns>
  93. /// <exception cref="CallbackCryptoException"></exception>
  94. private string Encrypt(string nonce, string plaintext)
  95. {
  96. byte[] randomBytes = Encoding.UTF8.GetBytes(nonce);
  97. byte[] plainTextBytes = Encoding.UTF8.GetBytes(plaintext);
  98. byte[] lengthByte = Utils.Int2Bytes(plainTextBytes.Length);
  99. byte[] clientIdBytes = Encoding.UTF8.GetBytes(_clientId);
  100. var bytestmp = new List<byte>();
  101. bytestmp.AddRange(randomBytes);
  102. bytestmp.AddRange(lengthByte);
  103. bytestmp.AddRange(plainTextBytes);
  104. bytestmp.AddRange(clientIdBytes);
  105. byte[] padBytes = PKCS7Padding.GetPaddingBytes(bytestmp.Count);
  106. bytestmp.AddRange(padBytes);
  107. byte[] unencrypted = bytestmp.ToArray();
  108. using (Aes aesAlg = Aes.Create())
  109. {
  110. aesAlg.Mode = CipherMode.CBC;
  111. aesAlg.Padding = PaddingMode.Zeros;
  112. aesAlg.Key = _aesKey;
  113. aesAlg.IV = _aesKey.ToList().Take(16).ToArray();
  114. // Create an encryptor to perform the stream transform.
  115. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
  116. byte[] encrypted = encryptor.TransformFinalBlock(unencrypted, 0, unencrypted.Length);
  117. return Convert.ToBase64String(encrypted, 0, encrypted.Length);
  118. }
  119. }
  120. /// <summary>
  121. /// 对密文进行解密
  122. /// </summary>
  123. /// <param name="text">需要解密的密文</param>
  124. /// <returns>解密得到的明文</returns>
  125. /// <exception cref="CallbackCryptoException"></exception>
  126. private string Decrypt(string text)
  127. {
  128. byte[] originalArr;
  129. byte[] toEncryptArray = Convert.FromBase64String(text);
  130. using (Aes aesAlg = Aes.Create())
  131. {
  132. aesAlg.Mode = CipherMode.CBC;
  133. aesAlg.Padding = PaddingMode.Zeros;
  134. aesAlg.Key = _aesKey;
  135. aesAlg.IV = _aesKey.ToList().Take(16).ToArray();
  136. // Create a decryptor to perform the stream transform.
  137. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
  138. // Create the streams used for decryption.
  139. originalArr = decryptor.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
  140. }
  141. string plaintext;
  142. string msgClientId;
  143. // 去除补位字符
  144. byte[] bytes = PKCS7Padding.RemovePaddingBytes(originalArr);
  145. int plainTextLegth = Utils.Bytes2int(bytes.Skip(RANDOM_LENGTH).Take(4).ToArray());
  146. plaintext = Encoding.UTF8.GetString(bytes.Skip(RANDOM_LENGTH + 4).Take(plainTextLegth).ToArray());
  147. msgClientId = Encoding.UTF8.GetString(bytes.Skip(RANDOM_LENGTH + 4 + plainTextLegth).ToArray());
  148. return !msgClientId.Equals(_clientId)
  149. ? throw new Exception("计算解密文字clientId不匹配")
  150. : plaintext;
  151. }
  152. /// <summary>
  153. /// 生成数字签名
  154. /// </summary>
  155. /// <param name="timestamp">时间戳</param>
  156. /// <param name="nonce">随机串</param>
  157. /// <param name="encrypt">加密文本</param>
  158. /// <returns></returns>
  159. /// <exception cref="CallbackCryptoException"></exception>
  160. public string GetSignature(string timestamp, string nonce, string encrypt)
  161. {
  162. string[] array = new string[] { _clientId, timestamp, nonce, encrypt };
  163. Array.Sort(array, StringComparer.Ordinal);
  164. SHA1 sHA1 = SHA1.Create();
  165. byte[] digest = sHA1.ComputeHash(Encoding.ASCII.GetBytes(string.Join(string.Empty, array)));
  166. StringBuilder hexstr = new StringBuilder();
  167. for (int i = 0; i < digest.Length; i++)
  168. {
  169. hexstr.Append(((int)digest[i]).ToString("x2"));
  170. }
  171. return hexstr.ToString();
  172. }
  173. }
  174. /// <summary>
  175. /// 加解密工具类
  176. /// </summary>
  177. public class Utils
  178. {
  179. public static string GetRandomStr(int count)
  180. {
  181. string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  182. Random random = new Random();
  183. StringBuilder sb = new StringBuilder();
  184. for (int i = 0; i < count; i++)
  185. {
  186. int number = random.Next(chars.Length);
  187. sb.Append(chars[number]);
  188. }
  189. return sb.ToString();
  190. }
  191. /// <summary>
  192. /// int转byte数组,高位在前
  193. /// </summary>
  194. public static byte[] Int2Bytes(int number)
  195. {
  196. return new byte[]
  197. {
  198. (byte) (number >> 24 & 0xFF),
  199. (byte) (number >> 16 & 0xFF),
  200. (byte) (number >> 8 & 0xFF),
  201. (byte) (number & 0xFF)
  202. };
  203. }
  204. /// <summary>
  205. /// 高位在前bytes数组转int
  206. /// </summary>
  207. public static int Bytes2int(byte[] byteArr)
  208. {
  209. int count = 0;
  210. for (int i = 0; i < 4; ++i)
  211. {
  212. count <<= 8;
  213. count |= byteArr[i] & 255;
  214. }
  215. return count;
  216. }
  217. }
  218. /// <summary>
  219. /// PKCS7算法的加密填充
  220. /// </summary>
  221. public class PKCS7Padding
  222. {
  223. private static readonly int BLOCK_SIZE = 32;
  224. /// <summary>
  225. /// 填充mode字节
  226. /// </summary>
  227. /// <param name="count"></param>
  228. public static byte[] GetPaddingBytes(int count)
  229. {
  230. int amountToPad = BLOCK_SIZE - count % BLOCK_SIZE;
  231. if (amountToPad == 0)
  232. {
  233. amountToPad = BLOCK_SIZE;
  234. }
  235. char padChr = Chr(amountToPad);
  236. string tmp = string.Empty;
  237. for (int index = 0; index < amountToPad; index++)
  238. {
  239. tmp += padChr;
  240. }
  241. return Encoding.UTF8.GetBytes(tmp);
  242. }
  243. /// <summary>
  244. /// 移除mode填充字节
  245. /// </summary>
  246. /// <param name="decrypted"></param>
  247. public static byte[] RemovePaddingBytes(byte[] decrypted)
  248. {
  249. int pad = decrypted[decrypted.Length - 1];
  250. if (pad < 1 || pad > BLOCK_SIZE)
  251. {
  252. pad = 0;
  253. }
  254. var output = new byte[decrypted.Length - pad];
  255. Array.Copy(decrypted, output, decrypted.Length - pad);
  256. return output;
  257. }
  258. private static char Chr(int a)
  259. {
  260. byte target = (byte)(a & 0xFF);
  261. return (char)target;
  262. }
  263. }
  264. }
  265. }