Created
August 28, 2013 22:52
-
-
Save jamesmontemagno/6372404 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Encrypt a string using AES | |
/// </summary> | |
/// <param name="clearString">String to encrypt</param> | |
/// <param name="salt">Salt string used for encryption</param> | |
/// <param name="password">Encryption password</param> | |
/// <returns>Encrypted string in case of success; otherwise - empty string</returns> | |
internal static string EncryptString(string clearString, string password, string salt) | |
{ | |
try | |
{ | |
using (Aes aes = new AesManaged()) | |
{ | |
var deriveBytes = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt)); | |
aes.Key = deriveBytes.GetBytes(128 / 8); | |
aes.IV = aes.Key; | |
using (var encryptionStream = new MemoryStream()) | |
{ | |
using (var encrypt = new CryptoStream(encryptionStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) | |
{ | |
byte[] utfD1 = Encoding.UTF8.GetBytes(clearString); | |
encrypt.Write(utfD1, 0, utfD1.Length); | |
encrypt.FlushFinalBlock(); | |
} | |
return Convert.ToBase64String(encryptionStream.ToArray()); | |
} | |
} | |
} | |
catch | |
{ | |
return ""; | |
} | |
} | |
/// <summary> | |
/// Decrypt encrypted string | |
/// </summary> | |
/// <param name="encryptedString">Encrypted string</param> | |
/// <param name="password">Password used for encryption</param> | |
/// <param name="salt">Salt string used for encryption</param> | |
/// <returns>Decrypted string if success; otherwise - empty string</returns> | |
public static string DecryptString(string encryptedString, string password, string salt) | |
{ | |
try | |
{ | |
using (Aes aes = new AesManaged()) | |
{ | |
var deriveBytes = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt)); | |
aes.Key = deriveBytes.GetBytes(128 / 8); | |
aes.IV = aes.Key; | |
using (var decryptionStream = new MemoryStream()) | |
{ | |
using (var decrypt = new CryptoStream(decryptionStream, aes.CreateDecryptor(), CryptoStreamMode.Write)) | |
{ | |
byte[] encryptedData = Convert.FromBase64String(encryptedString); | |
decrypt.Write(encryptedData, 0, encryptedData.Length); | |
decrypt.Flush(); | |
} | |
byte[] decryptedData = decryptionStream.ToArray(); | |
return Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length); | |
} | |
} | |
} | |
catch | |
{ | |
return ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment