Skip to content

Instantly share code, notes, and snippets.

@TehWardy
Created August 31, 2016 12:58
Show Gist options
  • Save TehWardy/8a92d7a3f81dd9a5257e3167325af7e3 to your computer and use it in GitHub Desktop.
Save TehWardy/8a92d7a3f81dd9a5257e3167325af7e3 to your computer and use it in GitHub Desktop.
public class AesCrypto<T> : ICrypto<T>
{
string DecryptionKey { get { return ((MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey")).DecryptionKey } }
string ValidationKey { get { return ((MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey")).ValidationKey } }
RijndaelManaged aesAlg;
ICryptoTransform encryptor;
ICryptoTransform decryptor;
public AesCrypto()
{
// generate the key from the shared secret and the salt
var key = new Rfc2898DeriveBytes(DecryptionKey, ASCIIEncoding.ASCII.GetBytes(ValidationKey));
// Create a RijndaelManaged object
var aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
// Create a encryptor and decryptor to perform the stream transform.
encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
}
public string Encrypt(T source)
{
var sourceString = JsonConvert.SerializeObject(source);
// Create the streams used for encryption.
using (var msEncrypt = new MemoryStream())
{
// prepend the IV
msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (var cryptoWriter = new StreamWriter(new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)))
{
cryptoWriter.Write(sourceString);
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
public T Decrypt(string sourceString)
{
// Create the streams used for encryption.
using (var msDecrypt = new MemoryStream())
{
// prepend the IV
msDecrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
msDecrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
using (var cryptoWriter = new StreamWriter(new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write)))
{
cryptoWriter.Write(sourceString);
return JsonConvert.DeserializeObject<T>(Convert.ToBase64String(msDecrypt.ToArray()));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment