/// <summary> /// Encrypts/decrypts a byte array /// </summary> /// <param name="buffer">Bytes to crypt</param> /// <param name="key">"Password" for encryption</param> /// <param name="iv">"Salt" for encryption. A starting point for encryption.</param> /// <param name="encrypt">Do you wish to encrypt or decrypt?</param> /// <param name="algorithm">Encryption algorithm. AES/DES/TripleDES</param> /// <returns></returns> public static byte[] Crypt(byte[] buffer, byte[] key, byte[] iv, bool encrypt = true, string algorithm = "aes") { AesCryptoServiceProvider aes = null; DESCryptoServiceProvider des = null; TripleDESCryptoServiceProvider tripsDes = null; ICryptoTransform cryptor; switch (algorithm.ToLower()) { case "aes": aes = new AesCryptoServiceProvider(); aes.Key = key; aes.IV = iv; //aes.Padding = PaddingMode.None; if (encrypt) cryptor = aes.CreateEncryptor(); else cryptor = aes.CreateDecryptor(); break; case "des": des = new DESCryptoServiceProvider(); des.Key = key; des.IV = iv; //des.Padding = PaddingMode.None; if (encrypt) cryptor = des.CreateEncryptor(); else cryptor = des.CreateDecryptor(); break; case "tripledes": tripsDes = new TripleDESCryptoServiceProvider(); tripsDes.Key = key; tripsDes.IV = iv; //tripsDes.Padding = PaddingMode.None; if (encrypt) cryptor = tripsDes.CreateEncryptor(); else cryptor = tripsDes.CreateDecryptor(); break; default: throw new ArgumentException(algorithm + " is not an implemented encryption algorithm. Use AES/DES/TripleDES."); } try { return cryptor.TransformFinalBlock(buffer, 0, buffer.Length); } catch (CryptographicException) { throw new ArgumentException("Ensure you have the right key/IV."); } finally { cryptor.Dispose(); if (aes != null) aes.Dispose(); if (des != null) des.Dispose(); if (tripsDes != null) tripsDes.Dispose(); } }
static void Main(string[] args) { const int n = 100 * 1000; var sw = new Stopwatch(); Random r = new Random(); var data = new byte[1024]; var key8B = new byte[8]; var key16B = new byte[16]; var key24B = new byte[24]; var key32B = new byte[32]; r.NextBytes(data); r.NextBytes(key8B); r.NextBytes(key16B); r.NextBytes(key24B); r.NextBytes(key32B); Action<string> outputToConsole = (s) => { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(s); }; // AES Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("AES"); var aes = new AesCryptoServiceProvider(); aes.Padding = PaddingMode.PKCS7; aes.Key = key16B; Action doAes = () => EncryptDecryptAndDispose(aes.CreateEncryptor(), aes.CreateDecryptor(), data); doAes.Repeat(n) .OutputPerformance(sw, outputToConsole)(); aes.Dispose(); // RSA Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("DES"); var des = new DESCryptoServiceProvider(); des.IV = key8B; des.Key = key8B; Action doDes = () => EncryptDecryptAndDispose(des.CreateEncryptor(), des.CreateDecryptor(), data); doDes.Repeat(n) .OutputPerformance(sw, outputToConsole)(); des.Dispose(); // RC2 Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("RC2"); var rc2 = new RC2CryptoServiceProvider(); rc2.IV = key8B; rc2.Key = key8B; Action doRc2 = () => EncryptDecryptAndDispose(rc2.CreateEncryptor(), rc2.CreateDecryptor(), data); doRc2.Repeat(n) .OutputPerformance(sw, outputToConsole)(); rc2.Dispose(); // Rijndael Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("Rijndael"); var rijndael = new RijndaelManaged(); rijndael.IV = key16B; rijndael.Key = key16B; Action doRijndael = () => EncryptDecryptAndDispose(rijndael.CreateEncryptor(), rijndael.CreateDecryptor(), data); doRijndael.Repeat(n) .OutputPerformance(sw, outputToConsole)(); rijndael.Dispose(); // 3DES Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("3DES"); var tripleDes = new TripleDESCryptoServiceProvider(); tripleDes.IV = key8B; tripleDes.Key = key24B; Action do3des = () => EncryptDecryptAndDispose(tripleDes.CreateEncryptor(), tripleDes.CreateDecryptor(), data); do3des.Repeat(n) .OutputPerformance(sw, outputToConsole)(); tripleDes.Dispose(); // RSA Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("RSA"); RSAParameters param = new RSAParameters(); param.Exponent = new byte[] {0, 1, 0}; var store = new X509Store(StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate cert = null; foreach (X509Certificate cer in store.Certificates) { if (cer != null) { cert = cer; break; } } param.Modulus = cert.GetPublicKey(); var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(param); Action doRsa = () => { var encryptedData = rsa.Encrypt(key32B, true); //var decryptedData = rsa.Decrypt(encryptedData, true); }; doRsa.Repeat(n) .OutputPerformance(sw, outputToConsole)(); rsa.Dispose(); Console.Read(); }
/// <summary> /// 加密字符串 /// </summary> /// <param name="basicData">源字符串</param> /// <returns>加密后的字符串</returns> public string EncryptString(string basicData) { DESCryptoServiceProvider provider = null; MemoryStream ms = null; CryptoStream cst = null; StreamWriter sw = null; try { byte[] byteKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_cryptographyKey); provider = new DESCryptoServiceProvider(); ms = new MemoryStream(); cst = new CryptoStream(ms, provider.CreateEncryptor(byteKey, byteKey), CryptoStreamMode.Write); sw = new StreamWriter(cst); sw.Write(basicData); sw.Flush(); cst.FlushFinalBlock(); sw.Flush(); return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); } catch { return null; } finally { if (provider != null) provider.Dispose(); if (ms != null) ms.Dispose(); if (cst != null) cst.Dispose(); if (sw != null) sw.Dispose(); } }
/// <summary> /// 解密字符串 /// </summary> /// <param name="basicData">加密了的字符串</param> /// <returns>解密后的字符串</returns> public string DecryptString(string basicData) { DESCryptoServiceProvider provider = null; MemoryStream ms = null; CryptoStream cst = null; StreamReader sr = null; try { byte[] byteEnc; byte[] byteKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_cryptographyKey); try { byteEnc = Convert.FromBase64String(basicData); } catch { return null; } provider = new DESCryptoServiceProvider(); ms = new MemoryStream(byteEnc); cst = new CryptoStream(ms, provider.CreateDecryptor(byteKey, byteKey), CryptoStreamMode.Read); sr = new StreamReader(cst); return sr.ReadToEnd(); } catch { return null; } finally { if (sr != null) sr.Dispose(); if (cst != null) cst.Dispose(); if (ms != null) ms.Dispose(); if (provider != null) provider.Dispose(); } }
/// <summary> /// Encrypt byte /// </summary> /// <param name="data">Bytes to encrypt.</param> /// <returns></returns> private byte[] EncryptToBytes(byte[] data) { DESCryptoServiceProvider desc = new DESCryptoServiceProvider(); try { desc.Key = mKey; desc.IV = mIV; desc.Mode = mMode; desc.Padding = mPaddingMode; return desc.CreateEncryptor().TransformFinalBlock(data, 0, data.Length); } finally { if (null != desc) { desc.Dispose(); } } }