2 using System.Collections.Generic;
5 using System.Security.Cryptography;
10 public static partial class StringEncryptor
61 public static string Encrypt(
string plainText,
65 int passwordIterations,
73 byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
74 byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
78 byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
84 PasswordDeriveBytes password =
new PasswordDeriveBytes(
92 byte[] keyBytes = password.GetBytes(keySize / 8);
95 RijndaelManaged symmetricKey =
new RijndaelManaged();
99 symmetricKey.Mode = CipherMode.CBC;
104 ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
109 MemoryStream memoryStream =
new MemoryStream();
112 CryptoStream cryptoStream =
new CryptoStream(memoryStream,
114 CryptoStreamMode.Write);
116 cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
119 cryptoStream.FlushFinalBlock();
122 byte[] cipherTextBytes = memoryStream.ToArray();
125 memoryStream.Close();
126 cryptoStream.Close();
129 string cipherText = Convert.ToBase64String(cipherTextBytes);
178 public static string Decrypt(
string cipherText,
181 string hashAlgorithm,
182 int passwordIterations,
190 byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
191 byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
194 byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
201 PasswordDeriveBytes password =
new PasswordDeriveBytes(
209 byte[] keyBytes = password.GetBytes(keySize / 8);
212 RijndaelManaged symmetricKey =
new RijndaelManaged();
216 symmetricKey.Mode = CipherMode.CBC;
221 ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
226 MemoryStream memoryStream =
new MemoryStream(cipherTextBytes);
229 CryptoStream cryptoStream =
new CryptoStream(memoryStream,
231 CryptoStreamMode.Read);
236 byte[] plainTextBytes =
new byte[cipherTextBytes.Length];
239 int decryptedByteCount = cryptoStream.Read(plainTextBytes,
241 plainTextBytes.Length);
244 memoryStream.Close();
245 cryptoStream.Close();
249 string plainText = Encoding.UTF8.GetString(plainTextBytes,