123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315 |
- using Alchemy.Core.Extensions;
- using System.Security.Cryptography;
- using System.Security.Cryptography.X509Certificates;
- using System.Text;
- namespace Alchemy.Core.Services
- {
- public class CryptoService
- {
- /// <summary>
- /// 将一条十六进制字符串转换为ASCII
- /// </summary>
- /// <param name="hexstring">一条十六进制字符串</param>
- /// <returns>返回一条ASCII码</returns>
- public static string HexStringToASCII(string hexstring)
- {
- byte[] bt = HexStringToBinary(hexstring);
- string lin = "";
- for (int i = 0; i < bt.Length; i++)
- {
- lin = lin + bt[i] + " ";
- }
- string[] ss = lin.Trim().Split(new char[] { ' ' });
- char[] c = new char[ss.Length];
- int a;
- for (int i = 0; i < c.Length; i++)
- {
- a = Convert.ToInt32(ss[i]);
- c[i] = Convert.ToChar(a);
- }
- string b = new string(c);
- return b;
- }
- /**/
- /// <summary>
- /// 16进制字符串转换为二进制数组
- /// </summary>
- /// <param name="hexstring">字符串每个字节之间都应该有空格,大多数的串口通讯资料上面的16进制都是字节之间都是用空格来分割的。</param>
- /// <returns>返回一个二进制字符串</returns>
- public static byte[] HexStringToBinary(string hexstring)
- {
- string[] tmpary = hexstring.Trim().Split(' ');
- byte[] buff = new byte[tmpary.Length];
- for (int i = 0; i < buff.Length; i++)
- {
- buff[i] = Convert.ToByte(tmpary[i], 16);
- }
- return buff;
- }
- /// <summary>
- /// AES 解密
- /// </summary>
- /// <param name="strEncoded"></param>
- /// <param name="strKey"></param>
- /// <returns></returns>
- public static string DecodeAes(string strEncoded, string strKey)
- {
- string strResult = string.Empty;
- byte[] encryptedBytes = Convert.FromBase64String(strEncoded);
- byte[] keyBytes = Encoding.UTF8.GetBytes(strKey);
- using (Aes aes = Aes.Create())
- {
- aes.Key = keyBytes;
- aes.IV = new byte[aes.BlockSize / 8];
- using (MemoryStream memStream = new MemoryStream())
- {
- using (CryptoStream cryptoStream = new CryptoStream(memStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
- {
- cryptoStream.Write(encryptedBytes, 0, encryptedBytes.Length);
- cryptoStream.FlushFinalBlock();
- byte[] decryptedBytes = memStream.ToArray();
- strResult = Encoding.UTF8.GetString(decryptedBytes);
- }
- }
- }
- return strResult;
- }
- /// <summary>
- /// 唯一识别ID加密算法
- /// </summary>
- /// <param name="numID"></param>
- /// <param name="strString"></param>
- /// <returns></returns>
- public static string EncodeUniqId(int numID, string strString)
- {
- string strUserIDHashed = EncodeMD5(numID.ToString());
- string strUserNameHashed = EncodeMD5(strString);
- string strDatetimeHashed = EncodeMD5(DateTimeService.Now());
- string value = EncodeMD5(EncodeBase64(strUserIDHashed + strUserNameHashed + strDatetimeHashed));
- return value;
- }
- /// <summary>
- /// 用户密码加密算法,使用基础加密算法
- /// </summary>
- /// <param name="strPwd">输入未加密的密码</param>
- /// <returns></returns>
- public static string EncodeUserPwd(string strPwd)
- {
- //string value = EncodeMD5(EncodeBase64(EncodeMD5(strPwd)));
- return EncodeMD5(strPwd);
- }
- /// <summary>
- /// 基础加密算法,先MD5再Base64再MD5
- /// </summary>
- /// <param name="strData">输入未加密的数据</param>
- /// <returns></returns>
- public static string EncodeBasicCrypto(string strData)
- {
- string value = EncodeMD5(EncodeBase64(EncodeMD5(strData)));
- return value;
- }
- /// <summary>
- /// 不安全加密算法,3次Base64
- /// </summary>
- /// <param name="strData"></param>
- /// <returns></returns>
- public static string EncodeUnsafeCrypto(string strData)
- {
- string value = EncodeBase64(EncodeBase64(EncodeBase64(strData)));
- return value;
- }
- public static string DecodeUnsafeCrypto(string strData)
- {
- string value = DecodeBase64(DecodeBase64(DecodeBase64(strData)));
- return value;
- }
- /// <summary>
- /// MD5加密,输出32位小写
- /// </summary>
- /// <param name="strData">输入字符串</param>
- /// <returns></returns>
- public static string EncodeMD5(string strData)
- {
- MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
- byte[] bytValue, bytHash;
- bytValue = Encoding.UTF8.GetBytes(strData);
- bytHash = md5.ComputeHash(bytValue);
- md5.Clear();
- string sTemp = "";
- for (int i = 0; i < bytHash.Length; i++)
- {
- sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
- }
- return sTemp.ToLower();
- }
- /// <summary>
- /// Base64加密
- /// </summary>
- /// <param name="strData">输入字符串</param>
- /// <returns></returns>
- public static string EncodeBase64(string strData)
- {
- byte[] arrData = Encoding.UTF8.GetBytes(strData);
- string strBase64 = Convert.ToBase64String(arrData);
- return strBase64;
- }
- /// <summary>
- /// Base64解密
- /// </summary>
- /// <param name="strData">输入字符串</param>
- /// <returns></returns>
- public static string DecodeBase64(string strData)
- {
- string strRaw = string.Empty;
- try
- {
- byte[] bytes = Convert.FromBase64String(strData);
- strRaw = Encoding.UTF8.GetString(bytes);
- }
- catch (Exception ex)
- {
- //throw new Exception(ex.Message);
- strRaw = strData;
- }
- return strRaw;
- }
- /// <summary>
- /// HMACSHA256加密算法
- /// </summary>
- /// <param name="strData"></param>
- /// <param name="strSecret"></param>
- /// <returns></returns>
- public static string EncodeHMACSHA256forWx(string strSecret)
- {
- return EncodeHMACSHA256("", strSecret);
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="strData"></param>
- /// <param name="strSecret"></param>
- /// <returns></returns>
- public static string EncodeHMACSHA256(string strData, string strSecret)
- {
- // 1. 将密钥字符串转换为UTF-8字节数组(不进行Base64解码)
- byte[] keyBytes = Encoding.UTF8.GetBytes(strSecret);
- // 2. 处理空字符串:使用空字节数组
- byte[] dataBytes = string.IsNullOrEmpty(strData)
- ? new byte[0]
- : Encoding.UTF8.GetBytes(strData);
- // 3. 计算HMAC-SHA256
- using var hmac = new HMACSHA256(keyBytes);
- byte[] hashBytes = hmac.ComputeHash(dataBytes);
- // 4. 转换为小写十六进制字符串
- return Convert.ToHexString(hashBytes).ToLowerInvariant();
- }
- /// <summary>
- /// 生成短链接
- /// </summary>
- /// <param name="strKey"></param>
- /// <param name="len"></param>
- /// <returns></returns>
- public static string EncodeShortUrl(string strKey, int len = 6)
- {
- string value = string.Empty;
- List<string> listFilter = new List<string>();
- listFilter.Add("o");
- listFilter.Add("0");
- listFilter.Add("O");
- listFilter.Add("I");
- listFilter.Add("l");
- listFilter.Add("i");
- listFilter.Add("1");
- for (int i = 0; i < len; i++)
- {
- string strChar = EncodeMD5(strKey + Guid.NewGuid().ToString()).ToUpper().Substring(i, 1);
- while (!listFilter.Contains(strChar))
- {
- strChar = EncodeMD5(strKey + Guid.NewGuid().ToString()).ToUpper().Substring(i, 1);
- }
- value += strChar;
- }
- return value;
- }
- /// <summary>
- /// 生成外部订单号
- /// </summary>
- /// <param name="strPrefix"></param>
- /// <returns></returns>
- public static string EncodeOutTradeNo(string strPrefix)
- {
- return strPrefix + EncodeUniqId(9999, Guid.NewGuid().ToString()).ToUpper();
- }
- /// <summary>
- /// RSA加密
- /// </summary>
- /// <param name="text"></param>
- /// <param name="publicKey"></param>
- /// <returns></returns>
- public static string EncodeRSA(string text, byte[] publicKey)
- {
- using (var x509 = new X509Certificate2(publicKey))
- {
- using (var rsa = (RSACryptoServiceProvider)x509.PublicKey.Key)
- {
- var buff = rsa.Encrypt(Encoding.UTF8.GetBytes(text), true);
- return Convert.ToBase64String(buff);
- }
- }
- }
- /// <summary>
- /// 计算文件的 MD5 值
- /// </summary>
- /// <param name="fileName">要计算 MD5 值的文件名和路径</param>
- /// <returns>MD5 值16进制字符串</returns>
- //public static string EncodeMd5FileHash(string fileName)
- //{
- // return HashFile(fileName, "md5");
- //}
- /// <summary>
- /// 计算文件的哈希值
- /// </summary>
- /// <param name="fileName">要计算哈希值的文件名和路径</param>
- /// <param name="algName">算法:sha1,md5</param>
- /// <returns>哈希值16进制字符串</returns>
- //private static string HashFile(string fileName, string algName)
- //{
- // if (!File.Exists(fileName))
- // return string.Empty;
- // FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
- // byte[] hashBytes = HashData(fs, algName);
- // fs.Close();
- // return ConvertService.ByteArrayToHexString(hashBytes);
- //}
- /// <summary>
- /// 计算哈希值
- /// </summary>
- /// <param name="stream">要计算哈希值的 Stream</param>
- /// <param name="algName">算法:sha1,md5</param>
- /// <returns>哈希值字节数组</returns>
- private static byte[] HashData(Stream stream, string algName)
- {
- HashAlgorithm algorithm;
- if (algName.IsNull())
- {
- throw new ArgumentNullException("algName 不能为 null");
- }
- if (string.Compare(algName, "sha1", true) == 0)
- {
- algorithm = SHA1.Create();
- }
- else
- {
- if (string.Compare(algName, "md5", true) != 0)
- {
- throw new Exception("algName 只能使用 sha1 或 md5");
- }
- algorithm = MD5.Create();
- }
- return algorithm.ComputeHash(stream);
- }
- }
- }
|