using System; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Miraclesoft.SecurityLibrary { ////// 使用加密服务提供程序 (CSP) 版本的数据加密标准 (System.Security.Cryptography.DES) 算法 /// public static class DESCryp { #region 加密 /// /// 使用默认密码(MiracleSoft)加密字符串 /// /// 明文字符串 /// 密文字符串 public static string Encrypt(string str) => Encrypt(str, "MiracleSoft"); /// /// 加密数据 /// /// 明文字符串 /// 密码 /// 密文字符串 public static string Encrypt(string str, string key) { var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(GetMD5(key)), IV = Encoding.ASCII.GetBytes(GetMD5(key)) }; var inputByteArray = Encoding.Default.GetBytes(str); using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); var ret = new StringBuilder(); foreach (var b in ms.ToArray()) ret.AppendFormat($"{b:X2}"); return ret.ToString(); } } } #endregion #region 解密 /// /// 使用默认密码(MiracleSoft)解密字符串 /// /// 密文字符串 /// 明文 public static string Decrypt(string str) => Decrypt(str, "MiracleSoft"); /// /// 解密数据 /// /// /// /// public static string Decrypt(string str, string key) { var des = new DESCryptoServiceProvider { Key = Encoding.ASCII.GetBytes(GetMD5(key)), IV = Encoding.ASCII.GetBytes(GetMD5(key)) }; var len = str.Length / 2; var inputByteArray = new byte[len]; for (var i = 0; i < len; i++) inputByteArray[i] = (byte)Convert.ToInt32(str.Substring(i * 2, 2), 16); using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.Default.GetString(ms.ToArray()); } } } #endregion #region MD5 /// /// 获取MD5字符串 /// /// 传入的字符串 /// MD5 private static string GetMD5(string str) { MD5 md5 = new MD5CryptoServiceProvider(); #region ///MD5CryptoServiceProvider 类MSDN详解 //https://msdn.microsoft.com/zh-cn/library/system.security.cryptography.md5cryptoserviceprovider(v=vs.110).aspx #endregion var md5char = md5.ComputeHash(Encoding.Unicode.GetBytes(str)); var result = md5char.Aggregate<byte, string>(null, (current, t) => current + t.ToString("x2")); return result.ToUpper(); } #endregion } }
using System; using System.Linq; using System.Security.Cryptography; using System.Text; namespace Miraclesoft.SecurityLibrary { ////// 得到随机哈希加密字符串,该加密不可逆. /// public static class HashCryp { /// /// 得到随机哈希加密字符串 /// /// public static string Security => HashEncoding(); /// ///生成随机长度随机字符串(10-64的长度) /// ///是否包含数字,true=包含,默认包含 ///是否包含小写字母,true=包含,默认包含 ///是否包含大写字母,true=包含,默认包含 ///是否包含特殊字符,true=包含,默认不包含 ///要包含的自定义字符 /// 指定长度的随机字符串 private static string GetRandomString(bool useNum = true, bool useLow = true, bool useUpp = true, bool useSpe = true, string custom = "") { var b = new byte[4]; new RNGCryptoServiceProvider().GetBytes(b); var rad = new Random(BitConverter.ToInt32(b, 0)); var length = rad.Next(10, 64); string result = null; if (useNum) custom += "0123456789"; if (useLow) custom += "abcdefghijklmnopqrstuvwxyz"; if (useUpp) custom += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; if (useSpe) custom += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; for (var i = 0; i < length; i++) result += custom.Substring(rad.Next(0, custom.Length - 1), 1); return result; } /// /// 哈希加密一个字符串 /// /// public static string HashEncoding() { var sHA512 = new SHA512Managed(); var unicodeEncoding = new UnicodeEncoding(); var value = sHA512.ComputeHash(unicodeEncoding.GetBytes(GetRandomString())); return value.Aggregate("", (current, o) => current + ((int)o + "O")); } } }
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace Miraclesoft.SecurityLibrary { /** * ############################################################################## * RSA 方式加密及RSA验证 * 说明KEY必须是XML的行式,返回的是字符串 * 有一点需要说明!!该加密方式有 长度 限制的!! * ############################################################################## */ /** * .Net Framework中提供的RSA算法规定,每次加密的字节数,不能超过密钥的长度值减去11, * 每次加密得到的密文长度,刚好是密钥的长度.所以,如果要加密较长的数据,可以采用数据截取的方法,分段加密. * 解密时肯定也要使用分段解密 */ ////// RSA加密解密及RSA签名和验证 /// 使用加密服务提供程序 (CSP) 提供的 System.Security.Cryptography.RSA 算法的实现执行非对称加密和解密 /// public class RSACryp { #region RSA 的密钥产生 /// /// RSA 的密钥产生 产生私钥和公钥 /// /// 当前RSA对象的密匙XML字符串(包括专用参数)--私钥 /// 当前RSA对象的密匙XML字符串(不包括专用参数)--公钥 public static void RSAKey(out string XmlPrivateKey, out string XmlPublicKey) { var rsa = new RSACryptoServiceProvider(); XmlPrivateKey = rsa.ToXmlString(true); XmlPublicKey = rsa.ToXmlString(false); } #endregion #region RSA的加密函数 /// /// 使用RSA的加密String(该方法存在长度限制) /// /// 当前RSA对象的密匙XML字符串(不包括专用参数)--公钥 /// 需要进行加密的字符串 /// 加密后的字符串 public static string RSAEncrypt(string XmlPublicKey, string Plaintext) => Convert.ToBase64String(RSAEncrypt(XmlPublicKey, new UnicodeEncoding().GetBytes(Plaintext))); /// /// 使用RSA的加密byte[](该方法存在长度限制) /// /// 当前RSA对象的密匙XML字符串(不包括专用参数)--公钥 /// 需要进行加密的字节数组 /// 加密后的字节数组 public static byte[] RSAEncrypt(string XmlPublicKey, byte[] Plaintext) { var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(XmlPublicKey); return rsa.Encrypt(Plaintext, false); } #endregion #region RSA的解密函数 /// /// RSA解密String(该方法存在长度限制) /// /// 当前RSA对象的密匙XML字符串(包括专用参数)--私钥 /// 需要进行解密的字符串 /// 解密后的字符串 public static string RSADecrypt(string XmlPrivateKey, string Ciphertext) => new UnicodeEncoding().GetString(RSADecrypt(XmlPrivateKey, Convert.FromBase64String(Ciphertext))); /// /// RSA解密byte[](该方法存在长度限制) /// /// 当前RSA对象的密匙XML字符串(包括专用参数)--私钥 /// 需要进行解密的字节数组 /// 解密后的字节数组 public static byte[] RSADecrypt(string XmlPrivateKey, byte[] Ciphertext) { var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(XmlPrivateKey); return rsa.Decrypt(Ciphertext, false); } #endregion #region 获取Hash描述表 /// /// 从字符串中取得Hash描述字节数组 /// /// 源字符串 /// /// Hash字节数组 public static byte[] GetHashByte(string source) { if (string.IsNullOrEmpty(source)) throw new ArgumentException("源字符串不能为空", nameof(source)); return HashAlgorithm.Create("MD5").ComputeHash(Encoding.GetEncoding("GB2312").GetBytes(source)); } /// /// 从字符串中取得Hash描述字符串 /// /// 源字符串 /// Hash字符串 public static string GetHashString(string source) => Convert.ToBase64String(GetHashByte(source)); /// /// 从文件中取得Hash描述字节数组 /// /// 文件流 /// /// Hash字节数组 public static byte[] GetFileHashByte(FileStream objFile) { if (objFile == null) throw new ArgumentNullException(nameof(objFile)); var arry = HashAlgorithm.Create("MD5").ComputeHash(objFile); objFile.Close(); return arry; } /// /// 从文件中取得Hash描述字符串 /// /// /// public static string GetFileHashString(FileStream objFile) => Convert.ToBase64String(GetFileHashByte(objFile)); #endregion #region RSA签名 /// /// RSA签名 /// /// 当前RSA对象的密匙XML字符串(包括专用参数)--私钥 /// 需要签名的字节数组数据 /// 签名后的字节数组数据 public static void SignatureFormatter(string XmlPrivateKey, byte[] HashbyteSignature, ref byte[] EncryptedSignatureByte) { var RSA = new RSACryptoServiceProvider(); RSA.FromXmlString(XmlPrivateKey); var RSAFormatter = new RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureByte = RSAFormatter.CreateSignature(HashbyteSignature); } /// /// RSA签名 /// /// 当前RSA对象的密匙XML字符串(包括专用参数)--私钥 /// 需要签名的字节数组数据 /// 签名后字符串 public static void SignatureFormatter(string XmlPrivateKey, byte[] HashbyteSignature, ref string EncryptedSignatureString) { byte[] EncryptedSignatureData = null; SignatureFormatter(XmlPrivateKey, HashbyteSignature, ref EncryptedSignatureData); EncryptedSignatureString = Convert.ToBase64String(EncryptedSignatureData); } /// /// RSA签名 /// /// 当前RSA对象的密匙XML字符串(包括专用参数)--私钥 /// 需要签名的字符串 /// 签名后的字节数组数据 /// public static void SignatureFormatter(string XmlPrivateKey, string HashStringSignature, ref byte[] EncryptedSignatureByte) => SignatureFormatter(XmlPrivateKey, Convert.FromBase64String(HashStringSignature), ref EncryptedSignatureByte); /// /// RSA签名 /// /// 当前RSA对象的密匙XML字符串(包括专用参数)--私钥 /// 需要签名的字符串 /// 签名后字符串 public static void SignatureFormatter(string XmlPrivateKey, string HashStringSignature, ref string EncryptedSignatureString) => SignatureFormatter(XmlPrivateKey, Convert.FromBase64String(HashStringSignature), ref EncryptedSignatureString); #endregion #region RSA 签名验证 /// /// RSA 签名验证 /// /// 当前RSA对象的密匙XML字符串(不包括专用参数)--公钥 /// 用RSA签名的字节数组数据 /// 要为该数据验证的签名字节数组 /// 如果 HashByteVerification 与使用指定的哈希算法和密钥在 SignatureByte 上计算出的签名匹配,则为 true;否则为 false. public static bool SignatureVerification(string XmlPublicKey, byte[] HashByteVerification, byte[] SignatureByte) { var RSA = new RSACryptoServiceProvider(); RSA.FromXmlString(XmlPublicKey); var RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); return RSADeformatter.VerifySignature(HashByteVerification, SignatureByte); } /// /// RSA 签名验证 /// /// 当前RSA对象的密匙XML字符串(不包括专用参数)--公钥 /// 用RSA签名的字符串数据 /// 要为该数据验证的签名字节数组 /// 如果 HashStringVerification 与使用指定的哈希算法和密钥在 SignatureByte 上计算出的签名匹配,则为 true;否则为 false. public static bool SignatureVerification(string XmlPublicKey, string HashStringVerification, byte[] SignatureByte) => SignatureVerification(XmlPublicKey, Convert.FromBase64String(HashStringVerification), SignatureByte); /// /// RSA 签名验证 /// /// 当前RSA对象的密匙XML字符串(不包括专用参数)--公钥 /// 用RSA签名的字节数组数据 /// 要为该数据验证的签名字符串 /// 如果 HashByteVerification 与使用指定的哈希算法和密钥在 SignatureString 上计算出的签名匹配,则为 true;否则为 false. public static bool SignatureVerification(string XmlPublicKey, byte[] HashByteVerification, string SignatureString) => SignatureVerification(XmlPublicKey, HashByteVerification, Convert.FromBase64String(SignatureString)); /// /// RSA 签名验证 /// /// 当前RSA对象的密匙XML字符串(不包括专用参数)--公钥 /// 用RSA签名的字符串数据 /// 要为该数据验证的签名字符串 /// 如果 HashStringVerification 与使用指定的哈希算法和密钥在 SignatureString 上计算出的签名匹配,则为 true;否则为 false. public static bool SignatureVerification(string XmlPublicKey, string HashStringVerification, string SignatureString) => SignatureVerification(XmlPublicKey, HashStringVerification, Convert.FromBase64String(SignatureString)); #endregion #region 不限长度 /// /// RSA加密 不限长度的加密版本 /// /// 公匙 /// 需要进行加密的字符串 /// 加密后的字符串 public static void RSAEncrypt(string XmlPublicKey, string Plaintext, ref string Ciphertext) { if (string.IsNullOrEmpty(Plaintext)) throw new Exception("加密字符串不能为空."); if (string.IsNullOrWhiteSpace(XmlPublicKey)) throw new ArgumentException("错误的公匙"); using (var rsaProvider = new RSACryptoServiceProvider()) { var inputBytes = Convert.FromBase64String(Plaintext); //有含义的字符串转化为字节流 rsaProvider.FromXmlString(XmlPublicKey); //载入公钥 var bufferSize = (rsaProvider.KeySize / 8) - 11; //单块最大长度 var buffer = new byte[bufferSize]; using (MemoryStream inputStream = new MemoryStream(inputBytes), outputStream = new MemoryStream()) { while (true) { //分段加密 var readSize = inputStream.Read(buffer, 0, bufferSize); if (readSize <= 0) break; var temp = new byte[readSize]; Array.Copy(buffer, 0, temp, 0, readSize); var encryptedBytes = rsaProvider.Encrypt(temp, false); outputStream.Write(encryptedBytes, 0, encryptedBytes.Length); } Ciphertext = Convert.ToBase64String(outputStream.ToArray()); //转化为字节流方便传输 } } } /// /// RSA解密 不限长度的解密版本 /// /// 私匙 /// 需要进行解密的字符串 /// 解密后的字符串 public static void RSADecrypt(string XmlPrivateKey, string Ciphertext, ref string Plaintext) { if (string.IsNullOrEmpty(Ciphertext)) throw new Exception("解密字符串不能为空."); if (string.IsNullOrWhiteSpace(XmlPrivateKey)) throw new ArgumentException("错误的私匙"); using (var rsaProvider = new RSACryptoServiceProvider()) { var inputBytes = Convert.FromBase64String(Ciphertext); rsaProvider.FromXmlString(XmlPrivateKey); var bufferSize = rsaProvider.KeySize / 8; var buffer = new byte[bufferSize]; using (MemoryStream inputStream = new MemoryStream(inputBytes), outputStream = new MemoryStream()) { while (true) { var readSize = inputStream.Read(buffer, 0, bufferSize); if (readSize <= 0) break; var temp = new byte[readSize]; Array.Copy(buffer, 0, temp, 0, readSize); var rawBytes = rsaProvider.Decrypt(temp, false); outputStream.Write(rawBytes, 0, rawBytes.Length); } Plaintext = new UnicodeEncoding().GetString((outputStream.ToArray())); } } } #endregion } }
using System; using System.Security.Cryptography; using System.Text; namespace Miraclesoft.SecurityLibrary { ////// 使用加密服务提供程序 (CSP) 版本 System.Security.Cryptography.TripleDES 算法 /// public static class TripleDESCryp { #region 使用 缺省密钥字符串 加密/解密String /// /// 使用缺省密钥字符串(yuwan.net)加密String /// /// 明文 /// 密文 public static string Encrypt(string original) => Encrypt(original, "yuwan.net"); /// /// 使用缺省密钥字符串(yuwan.net)解密String /// /// 密文 /// 明文 public static string Decrypt(string original) => Decrypt(original, "yuwan.net", Encoding.Default); #endregion #region 使用 给定密钥字符串 加密/解密String /// /// 使用给定密钥字符串加密String /// /// 原始文字 /// 密钥 /// 密文 public static string Encrypt(string original, string key) => Convert.ToBase64String(Encrypt(Encoding.Default.GetBytes(original), Encoding.Default.GetBytes(key))); /// /// 使用给定密钥字符串解密string /// /// 密文 /// 密钥 /// 明文 public static string Decrypt(string original, string key) => Decrypt(original, key, Encoding.Default); /// /// 使用给定密钥字符串解密string,返回指定编码方式明文 /// /// 密文 /// 密钥 /// 字符编码方案 /// 明文 public static string Decrypt(string encrypted, string key, Encoding encoding) => encoding.GetString(Decrypt(Convert.FromBase64String(encrypted), Encoding.Default.GetBytes(key))); #endregion #region 使用 缺省密钥字符串 加密/解密/byte[] /// /// 使用缺省密钥字符串(MiracleSoft)解密Byte[] /// /// 密文Byte[] /// 明文 public static byte[] Decrypt(byte[] encrypted) => Decrypt(encrypted, Encoding.Default.GetBytes("MiracleSoft")); /// /// 使用缺省密钥字符串(MiracleSoft)加密 /// /// 明文 /// 密文 public static byte[] Encrypt(byte[] original) => Encrypt(original, Encoding.Default.GetBytes("MiracleSoft")); #endregion #region 使用 给定密钥 加密/解密/byte[] /// /// 生成MD5摘要 /// /// 元数据 /// MD5摘要 public static byte[] MakeMD5(byte[] original) => new MD5CryptoServiceProvider().ComputeHash(original); /// /// 使用给定密钥加密 /// /// 明文 /// 密钥 /// 密文 public static byte[] Encrypt(byte[] original, byte[] key) { var des = new TripleDESCryptoServiceProvider { Key = MakeMD5(key), Mode = CipherMode.ECB }; return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length); } /// /// 使用给定密钥解密数据 /// /// 密文 /// 密钥 /// 明文 public static byte[] Decrypt(byte[] encrypted, byte[] key) { var des = new TripleDESCryptoServiceProvider { Key = MakeMD5(key), Mode = CipherMode.ECB }; return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length); } #endregion } }