| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277 |
- 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<T>()
- {
- 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<T>();
- }
- 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;
- }
- /// <summary>
- /// 字符串转16进制字节数组
- /// </summary>
- /// <param name="hexString"></param>
- /// <returns></returns>
- 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 + "/";
- }
- /// <summary>
- /// 字节数组转16进制字符串
- /// </summary>
- /// <param name="bytes"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 从汉字转换到16进制
- /// </summary>
- /// <param name="s"></param>
- /// <param name="charset">编码,如"utf-8","gb2312"</param>
- /// <param name="fenge">是否每字符用逗号分隔</param>
- /// <returns></returns>
- 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();
- }
- ///<summary>
- /// 从16进制转换成汉字
- /// </summary>
- /// <param name="hex"></param>
- /// <param name="charset">编码,如"utf-8","gb2312"</param>
- /// <returns></returns>
- 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);
- }
- /// <summary>
- /// 日期转换为时间戳(时间戳单位秒)
- /// </summary>
- /// <param name="TimeStamp"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 时间戳转换为日期(时间戳单位秒)
- /// </summary>
- /// <param name="TimeStamp"></param>
- /// <returns></returns>
- 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;
- }
- }
- }
|