using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Security.Cryptography; using System.IO; using System.Text; using Winsoft.GOV.XF.WebApi.WXCore.Models; using Senparc.Weixin.MP.AdvancedAPIs.OAuth; using Microsoft.AspNetCore.Http; namespace Winsoft.GOV.XF.WebApi.WXCore.Helpers { public static class Utilities { static ILoggerFactory _loggerFactory; public static void ConfigureLogger(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public static ILogger CreateLogger() { if (_loggerFactory == null) { throw new InvalidOperationException($"{nameof(ILogger)} is not configured. {nameof(ConfigureLogger)} must be called before use"); //_loggerFactory = new LoggerFactory().AddConsole().AddDebug(); } return _loggerFactory.CreateLogger(); } public static string ContentRootPath { get; set; } public static string AESEncrypt(this string input, string key) { byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input); byte[] passwordBytes = Encoding.UTF8.GetBytes(key); passwordBytes = SHA256.Create().ComputeHash(passwordBytes); byte[] bytesEncrypted = AESEncryptBytes(bytesToBeEncrypted, passwordBytes); string result = bytesEncrypted.ToHexStr(); return result; } private static byte[] AESEncryptBytes(byte[] bytesToBeEncrypted, byte[] passwordBytes) { byte[] encryptedBytes = null; var saltBytes = new byte[9] { 13, 34, 27, 67, 189, 255, 104, 219, 122 }; using (var ms = new MemoryStream()) { using (var AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(32); AES.IV = key.GetBytes(16); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length); cs.Close(); } encryptedBytes = ms.ToArray(); } } return encryptedBytes; } public static string AESDecrypt(this string input, string key) { byte[] bytesToBeDecrypted = input.ToHexBytes(); byte[] passwordBytes = Encoding.UTF8.GetBytes(key); passwordBytes = SHA256.Create().ComputeHash(passwordBytes); byte[] bytesDecrypted = AESDecryptBytes(bytesToBeDecrypted, passwordBytes); string result = Encoding.UTF8.GetString(bytesDecrypted); return result; } public static byte[] AESDecryptBytes(byte[] bytesToBeDecrypted, byte[] passwordBytes) { byte[] decryptedBytes = null; var saltBytes = new byte[9] { 13, 34, 27, 67, 189, 255, 104, 219, 122 }; using (var ms = new MemoryStream()) { using (var AES = new RijndaelManaged()) { AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(32); AES.IV = key.GetBytes(16); AES.Mode = CipherMode.CBC; using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length); cs.Close(); } decryptedBytes = ms.ToArray(); } } return decryptedBytes; } /// /// 字符串转16进制字节数组 /// /// /// public static byte[] ToHexBytes(this string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; } public static string GetBaseURL(this HttpRequest httpRequest) { string s = httpRequest.GetAbsoluteUri(); if (s.Last() == '/') return s; else return s + "/"; } /// /// 字节数组转16进制字符串 /// /// /// public static string ToHexStr(this byte[] bytes) { string returnStr = ""; if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { returnStr += bytes[i].ToString("X2"); } } return returnStr; } /// /// 从汉字转换到16进制 /// /// /// 编码,如"utf-8","gb2312" /// 是否每字符用逗号分隔 /// public static string ToHex(this string s, string charset, bool fenge) { if ((s.Length % 2) != 0) { s += " ";//空格 //throw new ArgumentException("s is not valid chinese string!"); } System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset); byte[] bytes = chs.GetBytes(s); string str = ""; for (int i = 0; i < bytes.Length; i++) { str += string.Format("{0:X}", bytes[i]); if (fenge && (i != bytes.Length - 1)) { str += string.Format("{0}", ","); } } return str.ToLower(); } /// /// 从16进制转换成汉字 /// /// /// 编码,如"utf-8","gb2312" /// public static string UnHex(this string hex, string charset) { if (hex == null) throw new ArgumentNullException("hex"); hex = hex.Replace(",", ""); hex = hex.Replace("\n", ""); hex = hex.Replace("\\", ""); hex = hex.Replace(" ", ""); if (hex.Length % 2 != 0) { hex += "20";//空格 } // 需要将 hex 转换成 byte 数组。 byte[] bytes = new byte[hex.Length / 2]; for (int i = 0; i < bytes.Length; i++) { try { // 每两个字符是一个 byte。 bytes[i] = byte.Parse(hex.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); } catch { // Rethrow an exception with custom message. throw new ArgumentException("hex is not a valid hex number!", "hex"); } } System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset); return chs.GetString(bytes); } /// /// 日期转换为时间戳(时间戳单位秒) /// /// /// public static long ToTimeStamp(this DateTime time) { DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return (long) (time.AddHours(-8) - Jan1st1970).TotalSeconds; } /// /// 时间戳转换为日期(时间戳单位秒) /// /// /// public static DateTime ToDateTime(this long timeStamp) { var start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return start.AddSeconds(timeStamp).AddHours(8); } public static WXUser CopyFromOAuthUserInfo(this WXUser user, OAuthUserInfo userInfo) { user.Nickname = userInfo.nickname; user.HeadimgUrl = userInfo.headimgurl; user.Province = userInfo.province; user.UnionId = userInfo.unionid; user.Sex = userInfo.sex; user.OpenId = userInfo.openid; return user; } } }