public bool encrypt(string path, string password, string destFile) { byte[] saltBytes = Encoding.ASCII.GetBytes(salt); byte[] valueBytes = zip(path); byte[] encryptedBytes; try { Rfc2898DeriveBytes passBytes = new Rfc2898DeriveBytes(password, saltBytes, iterations); byte[] keyBytes = passBytes.GetBytes(aes.KeySize / 8); aes.Key = keyBytes; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(valueBytes, 0, valueBytes.Length); } encryptedBytes = memoryStream.ToArray(); } aes.Clear(); File.WriteAllBytes(destFile, encryptedBytes); return(true); } catch (Exception e) { Logger.add(e.ToString()); return(false); } }
public static string Encrypt(string input) { byte[] vectorBytes = Encoding.ASCII.GetBytes(Vector); byte[] saltBytes = Encoding.ASCII.GetBytes(Salt); byte[] inputBytes = Encoding.UTF8.GetBytes(input); byte[] encrypted; using (var cipher = new AesManaged()) using (var passwordBytes = new PasswordDeriveBytes(PassPhrase, saltBytes, Hash, Iterations)) { byte[] keyBytes = passwordBytes.GetBytes(KeySize / 8); cipher.Mode = CipherMode.CBC; using (var encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) using (var ms = new MemoryStream()) using (var writer = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { writer.Write(inputBytes, 0, inputBytes.Length); writer.FlushFinalBlock(); encrypted = ms.ToArray(); } cipher.Clear(); } return(Convert.ToBase64String(encrypted)); }
internal static string DecryptData(string dataToDecrypt, string Key) { var tdes = new AesManaged { KeySize = 256, BlockSize = 128, Key = Encoding.UTF8.GetBytes(Key), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; string a = dataToDecrypt.Replace(" ", "+"); int mod4 = a.Length % 4; if (mod4 > 0) { a += new string('=', 4 - mod4); } var dataToDecryptBytes = Convert.FromBase64String(a); var decrypt = tdes.CreateDecryptor(); var deCipher = decrypt.TransformFinalBlock(dataToDecryptBytes, 0, dataToDecryptBytes.Length); tdes.Clear(); var plainText = Encoding.UTF8.GetString(deCipher); return(plainText); }
/// <summary> /// Encrypts the specified data using a 128-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be encrypted.</param> /// <param name="Key">The key used to encrypt the data.</param> /// <returns>A Base-64 string containing the encoded data.</returns> public static string Encrypt128Base64(string Data, byte[] Key) { AesManaged AES = null; var MS = new MemoryStream(); CryptoStream CS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesManaged { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV }; CS = new CryptoStream(MS, AES.CreateEncryptor(), CryptoStreamMode.Write); CS.Write(System.Text.Encoding.UTF8.GetBytes(Data), 0, System.Text.Encoding.UTF8.GetByteCount(Data)); CS.FlushFinalBlock(); return(Convert.ToBase64String(MS.ToArray())); } finally { if (AES != null) { AES.Clear(); } if (CS != null) { CS.Dispose(); } MS.Dispose(); } }
/// <summary> /// Decrypts the specified data using a 128-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be decrypted.</param> /// <param name="Key">The key used to decrypt the data.</param> /// <returns>A string containing the decoded data.</returns> public static Stream Decrypt128Stream(Stream Data, byte[] Key) { AesManaged AES = null; CryptoStream CS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesManaged { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV }; CS = new CryptoStream(Data, AES.CreateDecryptor(), CryptoStreamMode.Read); var D = new byte[CS.Length]; CS.Read(D, 0, (int)CS.Length - 1); return(new MemoryStream(D)); } finally { if (AES != null) { AES.Clear(); } if (CS != null) { CS.Dispose(); } } }
/// <summary> /// Decrypts the specified data using a 128-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be decrypted.</param> /// <param name="Key">The key used to decrypt the data.</param> /// <returns>A string containing the decoded data.</returns> public static string Decrypt128String(Stream Data, byte[] Key) { AesManaged AES = null; CryptoStream CS = null; StreamReader DS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesManaged { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV }; CS = new CryptoStream(Data, AES.CreateDecryptor(), CryptoStreamMode.Read); DS = new StreamReader(CS); return(DS.ReadToEnd()); } finally { if (AES != null) { AES.Clear(); } if (CS != null) { CS.Dispose(); } if (DS != null) { DS.Dispose(); } } }
/// <summary> /// Encrypts the specified data using a 128-bit cipher. The key can be any length. /// </summary> /// <param name="Data">The data to be encrypted.</param> /// <param name="Key">The key used to encrypt the data.</param> /// <returns>A stream containing the encoded data.</returns> public static Stream Encrypt128Stream(byte[] Data, byte[] Key) { AesManaged AES = null; var MS = new MemoryStream(); CryptoStream CS = null; try { //Get the IV and length corrected Key. KeyData KeyData = GenerateKeyIV128(Key); //Create the AES crytpograhy object. AES = new AesManaged { BlockSize = 128, KeySize = 128, Key = KeyData.Key, IV = KeyData.IV }; CS = new CryptoStream(MS, AES.CreateEncryptor(), CryptoStreamMode.Write); CS.Write(Data, 0, Data.Length); CS.FlushFinalBlock(); return(MS); } finally { if (AES != null) { AES.Clear(); } if (CS != null) { CS.Dispose(); } MS.Dispose(); } }
public void DecryptData() { MemoryStream memoryStream = null; using (AesManaged aes = new AesManaged()) { //Generate Key and IV values for decryption Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(SaltValue), 10000); aes.Key = rfc2898.GetBytes(32); aes.IV = rfc2898.GetBytes(16); using (memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) { //Decrypt Data byte[] secret = Convert.FromBase64String(EncryptedData); cryptoStream.Write(secret, 0, secret.Length); cryptoStream.FlushFinalBlock(); byte[] decryptBytes = memoryStream.ToArray(); aes.Clear(); //Update values on UI thread Deployment.Current.Dispatcher.BeginInvoke(() => { DecryptedData = Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); }); } } } }
public static string Decrypt(string input) { byte[] vectorBytes = Encoding.ASCII.GetBytes(Vector); byte[] saltBytes = Encoding.ASCII.GetBytes(Salt); byte[] inputBytes = Convert.FromBase64String(input); byte[] decrypted; int decryptedByteCount = 0; using (var cipher = new AesManaged()) using (var passwordBytes = new PasswordDeriveBytes(PassPhrase, saltBytes, Hash, Iterations)) { byte[] keyBytes = passwordBytes.GetBytes(KeySize / 8); cipher.Mode = CipherMode.CBC; using (var decryptor = cipher.CreateDecryptor(keyBytes, vectorBytes)) using (var ms = new MemoryStream(inputBytes)) using (CryptoStream reader = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { decrypted = new byte[inputBytes.Length]; decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length); } cipher.Clear(); } return(Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount)); }
public string Decryption() { try { byte[] encrypted = Convert.FromBase64String(textInput.Text); MemoryStream ms = null; CryptoStream cs = null; StreamReader sr = null; Aes aes = new AesManaged(); aes.Key = key; aes.IV = new byte[16]; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); ms = new MemoryStream(encrypted); cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); sr = new StreamReader(cs); string decrypted = sr.ReadToEnd(); ms.Dispose(); cs.Dispose(); sr.Dispose(); if (aes != null) { aes.Clear(); } return(decrypted); } catch { MessageBox.Show("Text entered was not valid encrypted text."); return(""); } }
private byte[] DecryptManaged(byte[] Key, byte[] Vector, byte[] Data) { byte[] decryptedBytes; int count = 0; using (MemoryStream stream = new MemoryStream(Data)) { using (AesManaged cipher = new AesManaged()) { cipher.Mode = CipherMode.CBC; cipher.Padding = PaddingMode.None; using (ICryptoTransform decryptor = cipher.CreateDecryptor(Key, Vector)) { using (CryptoStream reader = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { decryptedBytes = new byte[stream.Length]; count = reader.Read(decryptedBytes, 0, decryptedBytes.Length); } } cipher.Clear(); } } return(decryptedBytes); }
public static string Decrypt(string card, string salt, string passwd, int bits) { try { AesManaged AES = new AesManaged(); Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(passwd, Encoding.UTF8.GetBytes(salt)); Byte[] Data = Convert.FromBase64String(card); AES.BlockSize = 128; AES.KeySize = bits; AES.Key = rfc.GetBytes(AES.KeySize / 8); AES.IV = rfc.GetBytes(AES.BlockSize / 8); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(Data, 0, Data.Length); cs.FlushFinalBlock(); cs.Close(); string res = (string)Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); AES.Clear(); return(res); } catch (Exception e) { return(e.Message.ToString()); } }
public void EncryptData() { using (AesManaged aes = new AesManaged()) { Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(SaltValue), 10000); aes.Key = rfc2898.GetBytes(32); aes.IV = rfc2898.GetBytes(16); using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { //Encrypt Data with created CryptoStream byte[] secret = Encoding.UTF8.GetBytes(DataToEncrypt); cryptoStream.Write(secret, 0, secret.Length); cryptoStream.FlushFinalBlock(); aes.Clear(); //Set values on UI thread Deployment.Current.Dispatcher.BeginInvoke(() => { EncryptedData = Convert.ToBase64String(memoryStream.ToArray()); }); } } } }
///<summary>Encrypts signature text and returns a base 64 string so that it can go directly into the database.</summary> public string Encryption(string encrypt) { byte[] ecryptBytes = Encoding.UTF8.GetBytes(encrypt); MemoryStream ms = new MemoryStream(); CryptoStream cs = null; Aes aes = new AesManaged(); aes.Key = key; aes.IV = new byte[16]; ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(ecryptBytes, 0, ecryptBytes.Length); cs.FlushFinalBlock(); byte[] encryptedBytes = new byte[ms.Length]; ms.Position = 0; ms.Read(encryptedBytes, 0, (int)ms.Length); cs.Dispose(); ms.Dispose(); if (aes != null) { aes.Clear(); } return(Convert.ToBase64String(encryptedBytes)); }
public static byte[] Encrypt(byte[] toEncrypt, byte[] key) { byte[] results = new byte[0]; try { AesManaged tdes = new AesManaged(); tdes.Key = key; tdes.Mode = CipherMode.ECB; tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncrypt, 0, toEncrypt.Length); tdes.Clear(); results = resultArray; } catch { throw new Exception("Failed : key invalid"); } return(results); }
public string Generate(string name, string email) { byte[] keyBytes; using (AesManaged aesManaged = new AesManaged()) { byte[] vec = Encoding.UTF8.GetBytes(productVector); byte[] salt = Encoding.UTF8.GetBytes(productSalt); byte[] clearText = Encoding.UTF8.GetBytes(name + "|" + email); PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(productSec, salt, "SHA1", 2); byte[] key = passwordDeriveBytes.GetBytes(32); aesManaged.Mode = CipherMode.CBC; using (ICryptoTransform cryptoTransform = aesManaged.CreateEncryptor(key, vec)) { using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write)) { cryptoStream.Write(clearText, 0, clearText.Length); cryptoStream.FlushFinalBlock(); keyBytes = memoryStream.ToArray(); } } } aesManaged.Clear(); } return(Convert.ToBase64String(keyBytes)); }
public static string Encrypt(string encrypt) { UTF8Encoding enc = new UTF8Encoding(); byte[] arrayEncryptBytes = Encoding.UTF8.GetBytes(encrypt); MemoryStream ms = new MemoryStream(); CryptoStream cs = null; Aes aes = new AesManaged(); aes.Key = enc.GetBytes("AKQjlLUjlcABVbqp"); aes.IV = new byte[16]; ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(arrayEncryptBytes, 0, arrayEncryptBytes.Length); cs.FlushFinalBlock(); byte[] retval = new byte[ms.Length]; ms.Position = 0; ms.Read(retval, 0, (int)ms.Length); cs.Dispose(); ms.Dispose(); if (aes != null) { aes.Clear(); } return(Convert.ToBase64String(retval)); }
public static string Encrypt(string plainText, string password) { Contract.Requires(!string.IsNullOrWhiteSpace(plainText)); Contract.Requires(!string.IsNullOrWhiteSpace(password)); Contract.Ensures(!string.IsNullOrWhiteSpace(Contract.Result <string>())); var hashProvider = new SHA256CryptoServiceProvider(); var algorithm = new AesManaged { Key = hashProvider.ComputeHash(_utf8.GetBytes(password)), Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; try { using (var encryptor = algorithm.CreateEncryptor()) { var abData = _utf8.GetBytes(plainText); var abResult = encryptor.TransformFinalBlock(abData, 0, abData.Length); var result = System.Convert.ToBase64String(abResult); return(result); } } finally { algorithm.Clear(); algorithm.Dispose(); hashProvider.Clear(); hashProvider.Dispose(); } }
/// <summary> /// AES解密 /// </summary> /// <param name="decryptStr">待解密的字符串</param> /// <param name="key">加密密钥,Key是24位</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string AES_Decrypt(string decryptStr, string key) { try { Byte[] bKey = new Byte[32]; string str = key.PadRight(bKey.Length); byte[] keyArray = Encoding.UTF8.GetBytes(str); Array.Copy(keyArray, bKey, bKey.Length); byte[] toEncryptArray = Convert.FromBase64String(decryptStr); var aes = new AesManaged() { Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, KeySize = 256, Key = bKey }; byte[] resultArray = aes.CreateDecryptor().TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); aes.Clear(); return(Encoding.UTF8.GetString(resultArray)); } catch (Exception ex) { // Console.WriteLine(ex.Message); return(decryptStr); } }
private byte[] EncryptManaged(byte[] Key, byte[] Vector, byte[] Data) { byte[] encryptedBytes; using (MemoryStream stream = new MemoryStream()) { using (AesManaged cipher = new AesManaged()) { cipher.Mode = CipherMode.CBC; cipher.KeySize = Key.Length * 8; cipher.BlockSize = Vector.Length * 8; cipher.IV = Vector; cipher.Padding = PaddingMode.None; using (ICryptoTransform encryptor = cipher.CreateEncryptor(Key, Vector)) { using (CryptoStream writer = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { writer.Write(Data, 0, Data.Length); writer.FlushFinalBlock(); encryptedBytes = stream.ToArray(); } } cipher.Clear(); } } return(encryptedBytes); }
public static string Decrypt(string encString) { try { byte[] encrypted = Convert.FromBase64String(encString); MemoryStream ms = null; CryptoStream cs = null; StreamReader sr = null; Aes aes = new AesManaged(); UTF8Encoding enc = new UTF8Encoding(); aes.Key = enc.GetBytes("AKQjlLUjlcABVbqp"); //Random string will be key aes.IV = new byte[16]; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); ms = new MemoryStream(encrypted); cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); sr = new StreamReader(cs); string decrypted = sr.ReadToEnd(); ms.Dispose(); cs.Dispose(); sr.Dispose(); if (aes != null) { aes.Clear(); } return(decrypted); } catch { MessageBox.Show("Text entered was not valid encrypted text."); return(""); } }
/// <summary> /// AES加密 /// </summary> /// <param name="encryptStr">待加密的字符串</param> /// <param name="key">加密密钥</param> /// <returns>加密成功返回加密后的字符串,失败返回源串</returns> public static string AES_Encrypt(string encryptStr, string key) { try { Byte[] bKey = new Byte[32]; string str = key.PadRight(bKey.Length); byte[] keyArray = Encoding.UTF8.GetBytes(str); Array.Copy(keyArray, bKey, bKey.Length); byte[] toEncryptArray = Encoding.UTF8.GetBytes(encryptStr); var aes = new AesManaged() { Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, KeySize = 256, Key = bKey }; var resultArray = aes.CreateEncryptor().TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); aes.Clear(); return(Convert.ToBase64String(resultArray, 0, resultArray.Length)); } catch (Exception) { return(encryptStr); } }
public string Encrypt(string value) { byte[] vectorBytes = Encoding.ASCII.GetBytes(_vector); byte[] saltBytes = Encoding.ASCII.GetBytes(_salt); byte[] valueBytes = Encoding.UTF8.GetBytes(value); byte[] encrypted; using (var cipher = new AesManaged()) { var _passwordBytes = new Rfc2898DeriveBytes(_password, saltBytes, _iterations); byte[] keyBytes = _passwordBytes.GetBytes(_keySize / 8); cipher.Mode = CipherMode.CBC; using (ICryptoTransform encryptor = cipher.CreateEncryptor(keyBytes, vectorBytes)) { using (var to = new MemoryStream()) { using (var writer = new CryptoStream(to, encryptor, CryptoStreamMode.Write)) { writer.Write(valueBytes, 0, valueBytes.Length); writer.FlushFinalBlock(); encrypted = to.ToArray(); } } } cipher.Clear(); } return(Convert.ToBase64String(encrypted)); }
public static string Decrypt(string str, byte[] key) { //No need to check RemotingRole; no call to db. if (str == "") { return(""); } try { byte[] encrypted = Convert.FromBase64String(str); MemoryStream ms = null; CryptoStream cs = null; StreamReader sr = null; Aes aes = new AesManaged(); aes.Key = key; aes.IV = new byte[16]; ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); ms = new MemoryStream(encrypted); cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); sr = new StreamReader(cs); string decrypted = sr.ReadToEnd(); ms.Dispose(); cs.Dispose(); sr.Dispose(); if (aes != null) { aes.Clear(); } return(decrypted); } catch { //MessageBox.Show("Text entered was not valid encrypted text."); return(""); } }
///<summary>Encrypts signature text and returns a base 64 string so that it can go directly into the database.</summary> public static string Encrypt(string str, byte[] key) { //No need to check RemotingRole; no call to db. if (str == "") { return(""); } byte[] ecryptBytes = Encoding.UTF8.GetBytes(str); MemoryStream ms = new MemoryStream(); CryptoStream cs = null; Aes aes = new AesManaged(); aes.Key = key; aes.IV = new byte[16]; ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(ecryptBytes, 0, ecryptBytes.Length); cs.FlushFinalBlock(); byte[] encryptedBytes = new byte[ms.Length]; ms.Position = 0; ms.Read(encryptedBytes, 0, (int)ms.Length); cs.Dispose(); ms.Dispose(); if (aes != null) { aes.Clear(); } return(Convert.ToBase64String(encryptedBytes)); }
public static string Decrypt(byte[] toEncryptArray, byte[] key) { string results = ""; try { AesManaged aes = new AesManaged(); aes.Key = key; aes.Mode = CipherMode.ECB; aes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = aes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); aes.Clear(); results = Encoding.UTF8.GetString(resultArray); } catch { throw new Exception("Failed : key invalid"); } return(results); }
public static void GenAesKeyPair(ref byte[] key, ref byte[] iv) { using (Aes aes = new AesManaged()) { aes.KeySize = ConfigurationManager.CHIPER_KEY_SIZE; aes.Mode = ConfigurationManager.CHIPER_MODE; aes.Padding = ConfigurationManager.CHIPER_PADDING_MODE; aes.GenerateIV(); aes.GenerateKey(); byte[] volatileKey = aes.Key; byte[] volatileIv = aes.IV; key = new byte[volatileKey.Length]; iv = new byte[volatileIv.Length]; Array.Copy(volatileKey, key, volatileKey.Length); Array.Copy(volatileIv, iv, volatileIv.Length); Common.ClearArray(ref volatileKey); Common.ClearArray(ref volatileIv); aes.Clear(); } }
/// <summary> /// Encrypt the plaintext string with the given passphrase and returns the /// encrypted string in base64 format. /// </summary> /// <param name="plainText">The string to be encrypted</param> /// <param name="passPhrase">The passphrase to use in the encryption</param> /// <returns>The encrypted string</returns> internal static string Encrypt(string plainText, string passPhrase) { AesManaged aes = null; MemoryStream memoryStream = null; CryptoStream cryptoStream = null; byte[] cipherTextBytes; try { byte[] salt1 = new byte[SaltLength]; using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider()) { rngCsp.GetBytes(salt1); } Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(passPhrase, salt1, 10000); // Create AES algorithm aes = new AesManaged { Key = rfc2898.GetBytes(32), IV = rfc2898.GetBytes(16) }; // Create Memory and Crypto Streams memoryStream = new MemoryStream(); cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write); // Encrypt Data byte[] data = Encoding.UTF8.GetBytes(plainText); cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); byte[] encryptionStream = memoryStream.ToArray(); // Append the salt to the end of the encrypted string cipherTextBytes = new byte[encryptionStream.Length + salt1.Length]; Buffer.BlockCopy(encryptionStream, 0, cipherTextBytes, 0, encryptionStream.Length); Buffer.BlockCopy(salt1, 0, cipherTextBytes, encryptionStream.Length, salt1.Length); } finally { if (cryptoStream != null) { cryptoStream.Close(); memoryStream = null; // Because CryptoStream will dispose of it. } if (memoryStream != null) { memoryStream.Close(); } if (aes != null) { aes.Clear(); } } return(Convert.ToBase64String(cipherTextBytes)); }
public static string Decrypt(string dataToDecrypt) { AesManaged aes = null; MemoryStream memoryStream = null; try { //Generate a Key based on a Password and HMACSHA1 pseudo-random number generator //Salt must be at least 8 bytes long //Use an iteration count of at least 1000 Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(Salt), 10000); //Create AES algorithm aes = new AesManaged(); //Key derived from byte array with 32 pseudo-random key bytes aes.Key = rfc2898.GetBytes(32); //IV derived from byte array with 16 pseudo-random key bytes aes.IV = rfc2898.GetBytes(16); //Create Memory and Crypto Streams memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write); //Decrypt Data byte[] data = Convert.FromBase64String(dataToDecrypt); cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); //Return Decrypted String byte[] decryptBytes = memoryStream.ToArray(); //Dispose if (cryptoStream != null) { cryptoStream.Dispose(); } //Retval return(Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length)); } catch (Exception ex) { return(null); } finally { if (memoryStream != null) { memoryStream.Dispose(); } if (aes != null) { aes.Clear(); } } }
/// <summary> /// Decrypt the given string. Assumes the string was encrypted using /// EncryptStringAES(), using an identical sharedSecret. /// </summary> /// <param name="cipherText">The text to decrypt.</param> /// <param name="sharedSecret">A password used to generate a key for decryption.</param> public static string DecryptStringAES(string cipherText, string sharedSecret) { if (string.IsNullOrEmpty(cipherText)) { throw new ArgumentNullException("cipherText"); } if (string.IsNullOrEmpty(sharedSecret)) { throw new ArgumentNullException("sharedSecret"); } // Declare the RijndaelManaged object // used to decrypt the data. AesManaged aesAlg = null; // Declare the string used to hold // the decrypted text. string plaintext = null; try { // generate the key from the shared secret and the salt Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); // Create a RijndaelManaged object // with the specified key and IV. aesAlg = new AesManaged(); aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8); // Create a decrytor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. byte[] bytes = Convert.FromBase64String(cipherText); using (MemoryStream msDecrypt = new MemoryStream(bytes)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } finally { // Clear the RijndaelManaged object. if (aesAlg != null) { aesAlg.Clear(); } } return(plaintext); }