using System; using System.IO; using System.Text; using System.Web.Security; using System.Security.Cryptography; namespace SHJX.Service.Common.Extend { /// /// 加密 /// public static class Encryption { /// /// MD5字符串加密 /// /// /// 加密后字符串 public static string GenerateMd5(this string str) { using var md = MD5.Create(); var buffer = Encoding.Default.GetBytes(str); //开始加密 var newBuffer = md.ComputeHash(buffer); var sb = new StringBuilder(); foreach (var item in newBuffer) { sb.Append(item.ToString("x2")); } return sb.ToString(); } /// /// MD5流加密 /// /// /// public static string GenerateMd5(this Stream inputStream) { using var md = MD5.Create(); //开始加密 var newBuffer = md.ComputeHash(inputStream); var sb = new StringBuilder(); foreach (var item in newBuffer) { sb.Append(item.ToString("x2")); } return sb.ToString(); } /// /// DES数据加密 /// /// 目标值 /// 密钥 /// 加密值 public static string Encrypt(this string targetValue, string key) { if (string.IsNullOrEmpty(targetValue)) return string.Empty; var returnValue = new StringBuilder(); var des = new DESCryptoServiceProvider(); var inputByteArray = Encoding.Default.GetBytes(targetValue); // 通过两次哈希密码设置对称算法的初始化向量 des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")?.Substring(0, 8)!, "sha1")?.Substring(0, 8)!); // 通过两次哈希密码设置算法的机密密钥 des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5")?.Substring(0, 8)!, "md5")?.Substring(0, 8)!); var ms = new MemoryStream(); var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); foreach (byte b in ms.ToArray()) { returnValue.AppendFormat("{0:X2}", b); } return returnValue.ToString(); } /// /// DES数据解密 /// /// /// /// public static string Decrypt(this string targetValue, string key) { if (string.IsNullOrEmpty(targetValue)) return string.Empty; // 定义DES加密对象 var des = new DESCryptoServiceProvider(); int len = targetValue.Length / 2; var inputByteArray = new byte[len]; int x, i; for (x = 0; x < len; x++) { i = Convert.ToInt32(targetValue.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } // 通过两次哈希密码设置对称算法的初始化向量 des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5") ?.Substring(0, 8)!, "sha1")?.Substring(0, 8)!); // 通过两次哈希密码设置算法的机密密钥 des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5") ?.Substring(0, 8)!, "md5")?.Substring(0, 8)!); // 定义内存流 var ms = new MemoryStream(); // 定义加密流 var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.Default.GetString(ms.ToArray()); } } }