static class CryptoHelper { //--//-------------------------------------------------------- public enum IterationStrength { MasterKey = 4096, GeneralKey = 1024 }; //--//-------------------------------------------------------- public static string CreateSaltAsBase64String() { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte [] salt = new byte[8]; rng.GetBytes(salt); return Convert.ToBase64String(salt); } //--//-------------------------------------------------------- public static byte[] Get256BitPasswordFromPBKDF2(byte[] password, string salt, IterationStrength iterations) { Rfc2898DeriveBytes keyBytes = CreatePBKDF2Key(password, salt, iterations); return keyBytes.GetBytes(32); } //--//-------------------------------------------------------- private static Rfc2898DeriveBytes CreatePBKDF2Key(byte[] password, string salt, IterationStrength iterations) { return new Rfc2898DeriveBytes(password, Convert.FromBase64String(salt), (int)iterations); } //--//-------------------------------------------------------- public static string EncryptData(string plainText, byte [] password, string salt, IterationStrength iterations) { Rfc2898DeriveBytes keyBytes = CreatePBKDF2Key(password, salt, iterations); RijndaelManaged alg = new RijndaelManaged(); alg.Key = keyBytes.GetBytes(32); alg.IV = keyBytes.GetBytes(16); MemoryStream encryptionStream = new MemoryStream(); CryptoStream encrypt = new CryptoStream(encryptionStream, alg.CreateEncryptor(), CryptoStreamMode.Write); byte[] data = Encoding.UTF8.GetBytes(plainText); encrypt.Write(data, 0, data.Length); encrypt.FlushFinalBlock(); encrypt.Close(); return Convert.ToBase64String(encryptionStream.ToArray()); } //--//-------------------------------------------------------- public static string DecryptData(string cipherText, byte[] password, string salt, IterationStrength iterations) { Rfc2898DeriveBytes keyBytes = CreatePBKDF2Key(password, salt, iterations); RijndaelManaged alg = new RijndaelManaged(); alg.Key = keyBytes.GetBytes(32); alg.IV = keyBytes.GetBytes(16); MemoryStream decryptionStreamBacking = new MemoryStream(); CryptoStream decrypt = new CryptoStream(decryptionStreamBacking, alg.CreateDecryptor(), CryptoStreamMode.Write); byte[] data = Convert.FromBase64String(cipherText); decrypt.Write(data, 0, data.Length); decrypt.Flush(); decrypt.Close(); return Encoding.UTF8.GetString(decryptionStreamBacking.ToArray()); } }