using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace CommonTool { public class SysSecurity { private static string _Key = "HaiTingA"; public static string Get8Key(string pcKey) { #pragma warning disable 618 return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pcKey, "md5")?.Substring(0, 8); #pragma warning restore 618 } public static string Encrypt(string pToEncrypt) { return Encrypt(pToEncrypt, _Key); } //加密方法 /// /// 加密一个字符串 /// /// 要加密的字符串 /// 密约 /// public static string Encrypt(string pToEncrypt, string sKey) { if (string.IsNullOrEmpty(pToEncrypt)) return ""; try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); des.Key = Encoding.ASCII.GetBytes(sKey); des.IV = Encoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } return ret.ToString(); } catch (Exception e) { throw e; } } public static string Decrypt(string pToDecrypt) { return Decrypt(pToDecrypt, _Key); } //解密方法 /// /// 解密一个字符串 /// /// 要解密的字符串 /// 解密钥 /// public static string Decrypt(string pToDecrypt, string sKey) { if (string.IsNullOrEmpty(pToDecrypt)) return ""; try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; for (int x = 0; x < pToDecrypt.Length / 2; x++) { int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } des.Key = Encoding.ASCII.GetBytes(sKey); des.IV = Encoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //StringBuilder ret = new StringBuilder(); return Encoding.Default.GetString(ms.ToArray()); } catch (Exception e) { throw e; } } //private static string _Key = "HaiTingA"; public static string Encrypt4CPlus(string pToEncrypt) { return Encrypt4CPlus(pToEncrypt, _Key); } public static string Encrypt4CPlus(string pToEncrypt, string sKey) { if (pToEncrypt.Length == 0) return ""; //byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 }; byte[] keys = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; try { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); /*des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);*/ des.Key = Encoding.Default.GetBytes(sKey); des.IV = keys; // des.Mode = CipherMode.ECB; des.Padding = PaddingMode.Zeros; // MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } return ret.ToString(); } catch (Exception e) { throw e; } } public static string Encrypt3Des(string strString, string strKey, Encoding encoding) { TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider(); des.Key = hashMd5.ComputeHash(encoding.GetBytes(strKey)); des.Mode = CipherMode.ECB; ICryptoTransform desEncrypt = des.CreateEncryptor(); byte[] buffer = encoding.GetBytes(strString); return Convert.ToBase64String(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)); } /// /// 解密 /// /// /// /// public static string Decrypt3Des(string strString, string strKey) { TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider(); des.Key = hashMd5.ComputeHash(Encoding.ASCII.GetBytes(strKey)); des.Mode = CipherMode.ECB; ICryptoTransform desDecrypt = des.CreateDecryptor(); string result; try { byte[] buffer = Convert.FromBase64String(strString); result = Encoding.ASCII.GetString(desDecrypt.TransformFinalBlock(buffer, 0, buffer.Length)); } catch (Exception e) { throw (new Exception("null", e)); } return result; } /// /// 解密base64 串 /// /// /// public static string Base64Decode(string messages) { if ((messages.Length % 4) != 0) { throw new ArgumentException("不是正确的BASE64编码,请检查。", "messages"); } if (!System.Text.RegularExpressions.Regex.IsMatch(messages, "^[A-Z0-9/+=]*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { throw new ArgumentException("包含不正确的BASE64编码,请检查。", "messages"); } string Base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; int page = messages.Length / 4; System.Collections.ArrayList outMessage = new System.Collections.ArrayList(page * 3); char[] message = messages.ToCharArray(); for (int i = 0; i < page; i++) { byte[] instr = new byte[4]; instr[0] = (byte)Base64Code.IndexOf(message[i * 4]); instr[1] = (byte)Base64Code.IndexOf(message[i * 4 + 1]); instr[2] = (byte)Base64Code.IndexOf(message[i * 4 + 2]); instr[3] = (byte)Base64Code.IndexOf(message[i * 4 + 3]); byte[] outstr = new byte[3]; outstr[0] = (byte)((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4)); if (instr[2] != 64) { outstr[1] = (byte)((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2)); } else { outstr[2] = 0; } if (instr[3] != 64) { outstr[2] = (byte)((instr[2] << 6) ^ instr[3]); } else { outstr[2] = 0; } outMessage.Add(outstr[0]); if (outstr[1] != 0) outMessage.Add(outstr[1]); if (outstr[2] != 0) outMessage.Add(outstr[2]); } // ReSharper disable once AssignNullToNotNullAttribute byte[] outbyte = (byte[])outMessage.ToArray(Type.GetType("System.Byte")); return Encoding.Default.GetString(outbyte); } } //=================================================== /// /// 此处定义的是DES加密,为了便于今后的管理和维护 /// 请不要随便改动密码,或者改变了密码后请一定要 /// 牢记先前的密码,否则将会照成不可预料的损失 /// public class DesEncrypt { #region "member fields" private string iv = "HaitingA";//SongHongSongHaitingA private readonly DES _des; #endregion "member fields" /// /// 构造函数 /// public DesEncrypt() { _des = new DESCryptoServiceProvider(); } #region "propertys" /// /// 设置加密密钥 /// public string EncryptKey { get; set; } = "YouYouBB"; /// /// 要加密字符的编码模式 /// public Encoding EncodingMode { get; set; } = new UnicodeEncoding(); #endregion "propertys" #region "methods" /// /// 加密字符串并返回加密后的结果 /// /// /// public string EncryptString(string str) { try { byte[] ivb = Encoding.ASCII.GetBytes(iv); byte[] keyb = Encoding.ASCII.GetBytes(EncryptKey);//得到加密密钥 byte[] toEncrypt = EncodingMode.GetBytes(str);//得到要加密的内容 byte[] encrypted; ICryptoTransform encryptor = _des.CreateEncryptor(keyb, ivb); MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); encrypted = msEncrypt.ToArray(); csEncrypt.Close(); msEncrypt.Close(); return EncodingMode.GetString(encrypted); } catch (Exception e) { throw e; } } /// /// 加密指定的文件,如果成功返回True,否则false /// /// 要加密的文件路径 /// 加密后的文件输出路径 public void EncryptFile(string filePath, string outPath) { bool isExist = File.Exists(filePath); if (isExist)//如果存在 { byte[] ivb = Encoding.ASCII.GetBytes(iv); byte[] keyb = Encoding.ASCII.GetBytes(EncryptKey); //得到要加密文件的字节流 FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(fin, EncodingMode); string dataStr = reader.ReadToEnd(); byte[] toEncrypt = EncodingMode.GetBytes(dataStr); fin.Close(); FileStream fout = new FileStream(outPath, FileMode.Create, FileAccess.Write); ICryptoTransform encryptor = _des.CreateEncryptor(keyb, ivb); CryptoStream csEncrypt = new CryptoStream(fout, encryptor, CryptoStreamMode.Write); try { //加密得到的文件字节流 csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); } catch (Exception err) { throw new ApplicationException(err.Message); } finally { try { fout.Close(); csEncrypt.Close(); } catch { // ignored } } } else { throw new FileNotFoundException("没有找到指定的文件"); } } /// /// 文件加密函数的重载版本,如果不指定输出路径, /// 那么原来的文件将被加密后的文件覆盖 /// /// public void EncryptFile(string filePath) { EncryptFile(filePath, filePath); } /// /// 解密给定的字符串 /// /// 要解密的字符 /// public string DecryptString(string str) { byte[] ivb = Encoding.ASCII.GetBytes(iv); byte[] keyb = Encoding.ASCII.GetBytes(EncryptKey); byte[] toDecrypt = EncodingMode.GetBytes(str); byte[] deCrypted = new byte[toDecrypt.Length]; ICryptoTransform deCryptor = _des.CreateDecryptor(keyb, ivb); MemoryStream msDecrypt = new MemoryStream(toDecrypt); CryptoStream csDecrypt = new CryptoStream(msDecrypt, deCryptor, CryptoStreamMode.Read); try { csDecrypt.Read(deCrypted, 0, deCrypted.Length); } catch (Exception err) { throw new ApplicationException(err.Message); } finally { try { msDecrypt.Close(); csDecrypt.Close(); } catch { // ignored } } return EncodingMode.GetString(deCrypted); } /// /// 解密指定的文件 /// /// 要解密的文件路径 /// 解密后的文件输出路径 public void DecryptFile(string filePath, string outPath) { bool isExist = File.Exists(filePath); if (isExist)//如果存在 { byte[] ivb = Encoding.ASCII.GetBytes(iv); byte[] keyb = Encoding.ASCII.GetBytes(EncryptKey); FileInfo file = new FileInfo(filePath); byte[] deCrypted = new byte[file.Length]; //得到要解密文件的字节流 FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read); //解密文件 try { ICryptoTransform decryptor = _des.CreateDecryptor(keyb, ivb); CryptoStream csDecrypt = new CryptoStream(fin, decryptor, CryptoStreamMode.Read); csDecrypt.Read(deCrypted, 0, deCrypted.Length); } catch (Exception err) { throw new ApplicationException(err.Message); } finally { try { fin.Close(); } catch { // ignored } } FileStream fout = new FileStream(outPath, FileMode.Create, FileAccess.Write); fout.Write(deCrypted, 0, deCrypted.Length); fout.Close(); } else { throw new FileNotFoundException("指定的解密文件没有找到"); } } /// /// 解密文件的重载版本,如果没有给出解密后文件的输出路径, /// 则解密后的文件将覆盖先前的文件 /// /// public void DecryptFile(string filePath) { DecryptFile(filePath, filePath); } #endregion "methods" } //=============================================================== /// /// MD5加密类,注意经MD5加密过的信息是不能转换回原始数据的 /// ,请不要在用户敏感的信息中使用此加密技术,比如用户的密码, /// 请尽量使用对称加密 /// public class Md5Encrypt { private readonly MD5 _md5; public Md5Encrypt() { _md5 = new MD5CryptoServiceProvider(); } /// /// 从字符串中获取散列值 /// /// 要计算散列值的字符串 /// public string GetMd5FromString(string str) { byte[] toCompute = Encoding.Unicode.GetBytes(str); byte[] hashed = _md5.ComputeHash(toCompute, 0, toCompute.Length); return Encoding.ASCII.GetString(hashed); } /// /// 根据文件来计算散列值 /// /// 要计算散列值的文件路径 /// public string GetMd5FromFile(string filePath) { bool isExist = File.Exists(filePath); if (isExist)//如果文件存在 { FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(stream, Encoding.Unicode); string str = reader.ReadToEnd(); byte[] toHash = Encoding.Unicode.GetBytes(str); byte[] hashed = _md5.ComputeHash(toHash, 0, toHash.Length); stream.Close(); return Encoding.ASCII.GetString(hashed); } //文件不存在 throw new FileNotFoundException("指定的文件没有找到"); } } //================================================================ /// /// 用于数字签名的hash类 /// public class MacTripleDesEncrypt { private string _key = "ksn168ch"; public MacTripleDesEncrypt() { Mact = new MACTripleDES(); } /// /// 获取或设置用于数字签名的密钥 /// public string Key { get { return _key; } set { int keyLength = value.Length; int[] keyAllowLengths = { 8, 16, 24 }; bool isRight = false; foreach (int i in keyAllowLengths) { if (keyLength == keyAllowLengths[i]) { isRight = true; break; } } if (!isRight) throw new ApplicationException("用于数字签名的密钥长度必须是8,16,24值之一"); _key = value; } } /// /// 获取或设置用于数字签名的用户数据 /// public byte[] Data { get; set; } public MACTripleDES Mact { get; set; } /// /// 得到签名后的hash值 /// /// public string GetHashValue() { if (Data == null) throw new Exception("没有设置要进行数字签名的用户" + "数据(property:Data)"); byte[] key = Encoding.ASCII.GetBytes(Key); Mact.Key = key; byte[] hashB = Mact.ComputeHash(Mact.ComputeHash(Data)); return Encoding.ASCII.GetString(hashB); } } }