Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Created June 27, 2011 12:13
Show Gist options
  • Save ChrisMcKee/1048752 to your computer and use it in GitHub Desktop.
Save ChrisMcKee/1048752 to your computer and use it in GitHub Desktop.
AES Encryption for Passing Parameters in the URL
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace xxx.xxxx.Shared.Application
{
public class AESEncryptionHelper
{
private static readonly byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private static readonly byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 };
private readonly ICryptoTransform _encryptor;
private readonly ICryptoTransform _decryptor;
private readonly UTF8Encoding encoder;
public AESEncryptionHelper()
{
var rm = new RijndaelManaged();
this._encryptor = rm.CreateEncryptor(Key, Vector);
this._decryptor = rm.CreateDecryptor(Key, Vector);
encoder = new UTF8Encoding();
}
private string Encrypt(string unencrypted)
{
return Convert.ToBase64String(Encrypt(encoder.GetBytes(unencrypted)));
}
private string Decrypt(string encrypted)
{
return encoder.GetString(Decrypt(Convert.FromBase64String(encrypted.Replace(" ", "+"))));
}
public string EncryptToUrl(string unencrypted)
{
return HttpUtility.UrlEncode(Encrypt(unencrypted));
}
public string DecryptFromUrl(string encrypted)
{
return Decrypt(HttpUtility.UrlDecode(encrypted));
}
public byte[] Encrypt(byte[] buffer)
{
MemoryStream encryptStream = new MemoryStream();
using (CryptoStream cs = new CryptoStream(encryptStream, this._encryptor, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
return encryptStream.ToArray();
}
public byte[] Decrypt(byte[] buffer)
{
MemoryStream decryptStream = new MemoryStream();
using (CryptoStream cs = new CryptoStream(decryptStream, this._decryptor, CryptoStreamMode.Write))
{
cs.Write(buffer, 0, buffer.Length);
}
return decryptStream.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment