Utilities.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using System.Security.Cryptography;
  7. using System.IO;
  8. using System.Text;
  9. using Winsoft.GOV.XF.WebApi.WXCore.Models;
  10. using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
  11. using Microsoft.AspNetCore.Http;
  12. namespace Winsoft.GOV.XF.WebApi.WXCore.Helpers
  13. {
  14. public static class Utilities
  15. {
  16. static ILoggerFactory _loggerFactory;
  17. public static void ConfigureLogger(ILoggerFactory loggerFactory)
  18. {
  19. _loggerFactory = loggerFactory;
  20. }
  21. public static ILogger CreateLogger<T>()
  22. {
  23. if (_loggerFactory == null)
  24. {
  25. throw new InvalidOperationException($"{nameof(ILogger)} is not configured. {nameof(ConfigureLogger)} must be called before use");
  26. //_loggerFactory = new LoggerFactory().AddConsole().AddDebug();
  27. }
  28. return _loggerFactory.CreateLogger<T>();
  29. }
  30. public static string ContentRootPath { get; set; }
  31. public static string AESEncrypt(this string input, string key)
  32. {
  33. byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
  34. byte[] passwordBytes = Encoding.UTF8.GetBytes(key);
  35. passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
  36. byte[] bytesEncrypted = AESEncryptBytes(bytesToBeEncrypted, passwordBytes);
  37. string result = bytesEncrypted.ToHexStr();
  38. return result;
  39. }
  40. private static byte[] AESEncryptBytes(byte[] bytesToBeEncrypted, byte[] passwordBytes)
  41. {
  42. byte[] encryptedBytes = null;
  43. var saltBytes = new byte[9] { 13, 34, 27, 67, 189, 255, 104, 219, 122 };
  44. using (var ms = new MemoryStream())
  45. {
  46. using (var AES = new RijndaelManaged())
  47. {
  48. AES.KeySize = 256;
  49. AES.BlockSize = 128;
  50. var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
  51. AES.Key = key.GetBytes(32);
  52. AES.IV = key.GetBytes(16);
  53. AES.Mode = CipherMode.CBC;
  54. using (var cs = new CryptoStream(ms, AES.CreateEncryptor(),
  55. CryptoStreamMode.Write))
  56. {
  57. cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
  58. cs.Close();
  59. }
  60. encryptedBytes = ms.ToArray();
  61. }
  62. }
  63. return encryptedBytes;
  64. }
  65. public static string AESDecrypt(this string input, string key)
  66. {
  67. byte[] bytesToBeDecrypted = input.ToHexBytes();
  68. byte[] passwordBytes = Encoding.UTF8.GetBytes(key);
  69. passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
  70. byte[] bytesDecrypted = AESDecryptBytes(bytesToBeDecrypted, passwordBytes);
  71. string result = Encoding.UTF8.GetString(bytesDecrypted);
  72. return result;
  73. }
  74. public static byte[] AESDecryptBytes(byte[] bytesToBeDecrypted, byte[] passwordBytes)
  75. {
  76. byte[] decryptedBytes = null;
  77. var saltBytes = new byte[9] { 13, 34, 27, 67, 189, 255, 104, 219, 122 };
  78. using (var ms = new MemoryStream())
  79. {
  80. using (var AES = new RijndaelManaged())
  81. {
  82. AES.KeySize = 256;
  83. AES.BlockSize = 128;
  84. var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
  85. AES.Key = key.GetBytes(32);
  86. AES.IV = key.GetBytes(16);
  87. AES.Mode = CipherMode.CBC;
  88. using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
  89. {
  90. cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
  91. cs.Close();
  92. }
  93. decryptedBytes = ms.ToArray();
  94. }
  95. }
  96. return decryptedBytes;
  97. }
  98. /// <summary>
  99. /// 字符串转16进制字节数组
  100. /// </summary>
  101. /// <param name="hexString"></param>
  102. /// <returns></returns>
  103. public static byte[] ToHexBytes(this string hexString)
  104. {
  105. hexString = hexString.Replace(" ", "");
  106. if ((hexString.Length % 2) != 0)
  107. hexString += " ";
  108. byte[] returnBytes = new byte[hexString.Length / 2];
  109. for (int i = 0; i < returnBytes.Length; i++)
  110. returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
  111. return returnBytes;
  112. }
  113. public static string GetBaseURL(this HttpRequest httpRequest)
  114. {
  115. string s = httpRequest.GetAbsoluteUri();
  116. if (s.Last() == '/')
  117. return s;
  118. else
  119. return s + "/";
  120. }
  121. /// <summary>
  122. /// 字节数组转16进制字符串
  123. /// </summary>
  124. /// <param name="bytes"></param>
  125. /// <returns></returns>
  126. public static string ToHexStr(this byte[] bytes)
  127. {
  128. string returnStr = "";
  129. if (bytes != null)
  130. {
  131. for (int i = 0; i < bytes.Length; i++)
  132. {
  133. returnStr += bytes[i].ToString("X2");
  134. }
  135. }
  136. return returnStr;
  137. }
  138. /// <summary>
  139. /// 从汉字转换到16进制
  140. /// </summary>
  141. /// <param name="s"></param>
  142. /// <param name="charset">编码,如"utf-8","gb2312"</param>
  143. /// <param name="fenge">是否每字符用逗号分隔</param>
  144. /// <returns></returns>
  145. public static string ToHex(this string s, string charset, bool fenge)
  146. {
  147. if ((s.Length % 2) != 0)
  148. {
  149. s += " ";//空格
  150. //throw new ArgumentException("s is not valid chinese string!");
  151. }
  152. System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
  153. byte[] bytes = chs.GetBytes(s);
  154. string str = "";
  155. for (int i = 0; i < bytes.Length; i++)
  156. {
  157. str += string.Format("{0:X}", bytes[i]);
  158. if (fenge && (i != bytes.Length - 1))
  159. {
  160. str += string.Format("{0}", ",");
  161. }
  162. }
  163. return str.ToLower();
  164. }
  165. ///<summary>
  166. /// 从16进制转换成汉字
  167. /// </summary>
  168. /// <param name="hex"></param>
  169. /// <param name="charset">编码,如"utf-8","gb2312"</param>
  170. /// <returns></returns>
  171. public static string UnHex(this string hex, string charset)
  172. {
  173. if (hex == null)
  174. throw new ArgumentNullException("hex");
  175. hex = hex.Replace(",", "");
  176. hex = hex.Replace("\n", "");
  177. hex = hex.Replace("\\", "");
  178. hex = hex.Replace(" ", "");
  179. if (hex.Length % 2 != 0)
  180. {
  181. hex += "20";//空格
  182. }
  183. // 需要将 hex 转换成 byte 数组。
  184. byte[] bytes = new byte[hex.Length / 2];
  185. for (int i = 0; i < bytes.Length; i++)
  186. {
  187. try
  188. {
  189. // 每两个字符是一个 byte。
  190. bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
  191. System.Globalization.NumberStyles.HexNumber);
  192. }
  193. catch
  194. {
  195. // Rethrow an exception with custom message.
  196. throw new ArgumentException("hex is not a valid hex number!", "hex");
  197. }
  198. }
  199. System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
  200. return chs.GetString(bytes);
  201. }
  202. /// <summary>
  203. /// 日期转换为时间戳(时间戳单位秒)
  204. /// </summary>
  205. /// <param name="TimeStamp"></param>
  206. /// <returns></returns>
  207. public static long ToTimeStamp(this DateTime time)
  208. {
  209. DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  210. return (long) (time.AddHours(-8) - Jan1st1970).TotalSeconds;
  211. }
  212. /// <summary>
  213. /// 时间戳转换为日期(时间戳单位秒)
  214. /// </summary>
  215. /// <param name="TimeStamp"></param>
  216. /// <returns></returns>
  217. public static DateTime ToDateTime(this long timeStamp)
  218. {
  219. var start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  220. return start.AddSeconds(timeStamp).AddHours(8);
  221. }
  222. public static WXUser CopyFromOAuthUserInfo(this WXUser user, OAuthUserInfo userInfo)
  223. {
  224. user.Nickname = userInfo.nickname;
  225. user.HeadimgUrl = userInfo.headimgurl;
  226. user.Province = userInfo.province;
  227. user.UnionId = userInfo.unionid;
  228. user.Sex = userInfo.sex;
  229. user.OpenId = userInfo.openid;
  230. return user;
  231. }
  232. }
  233. }