Encrypt/Decrypt
A while ago I was searching for some code to encrypt/decrypt values for a project in Silverlight. Just going to put the code here so that it may be of help to some poor soul. Following code essentially encrypts using AES. A decrypt function is also added. This is in case one doesn’t want to go the on-way MD5 way.
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Diagnostics;public static string Encrypt(string input)
{
string data = input;
byte[] utfdata = UTF8Encoding.UTF8.GetBytes(data);
byte[] saltBytes = UTF8Encoding.UTF8.GetBytes("addSaltToTaste");
AesManaged aes = new AesManaged();
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("thePassword", saltBytes);
// Setting Encryption parameters
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
aes.Key = rfc.GetBytes(aes.KeySize / 8);
aes.IV = rfc.GetBytes(aes.BlockSize / 8);
// Start Encryption
ICryptoTransform encryptTransf = aes.CreateEncryptor();
MemoryStream encryptStream = new MemoryStream();
CryptoStream encryptor = new CryptoStream(encryptStream, encryptTransf, CryptoStreamMode.Write);
encryptor.Write(utfdata, 0, utfdata.Length);
encryptor.Flush();
encryptor.Close();
// Output Encrypted Content
byte[] encryptBytes = encryptStream.ToArray();
string encryptedString = Convert.ToBase64String(encryptBytes);
Debug.WriteLine(encryptedString);
return encryptedString;
}private string Decrypt(string base64Input)
{
//byte[] encryptBytes = UTF8Encoding.UTF8.GetBytes(input);
byte[] encryptBytes = Convert.FromBase64String(base64Input);
byte[] saltBytes = Encoding.UTF8.GetBytes("addSaltToTaste");
AesManaged aes = new AesManaged();
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("thePassword", saltBytes);
// Set parameters
aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
aes.KeySize = aes.LegalKeySizes[0].MaxSize;
aes.Key = rfc.GetBytes(aes.KeySize / 8);
aes.IV = rfc.GetBytes(aes.BlockSize / 8);
// Start decryption
ICryptoTransform decryptTrans = aes.CreateDecryptor();
MemoryStream decryptStream = new MemoryStream();
CryptoStream decryptor = new CryptoStream(decryptStream, decryptTrans, CryptoStreamMode.Write);
decryptor.Write(encryptBytes, 0, encryptBytes.Length);
decryptor.Flush();
decryptor.Close();
// Write decrypted content
byte[] decryptBytes = decryptStream.ToArray();
string decryptedString = UTF8Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length);
//Debug.WriteLine(decryptedString);
return decryptedString;
}