URL QueryString with Encryption & Decryption
For the security concern we have to pass querystring value in encrypted mode, and while we retrieve querystring value we need to decrypt it and use it.Here, I mentioned..
- Plain text encryption
- Decryption of encrypted text
- URL encode (System.Web.HttpUtility.UrlEncode)
- URL decode (System.Web.HttpUtility.UrlDecode)
Here, I have mentioned URL querystring encryption and decryption...
Encryption
protected void Submit(object sender, EventArgs e)
{
string username = "anrorathod";
string userid = "2279";
string uname = HttpUtility.UrlEncode(Encrypt(username));
string uid = HttpUtility.UrlEncode(Encrypt(userid));
Response.Redirect(string.Format("~/newpagename.aspx?name={0}&id={1}", uname, uid));
}
private string Encrypt(string textToEncrypt)
{
string EncryptionKey = "Writeyourkeyhere-Youcanwriteanything";
byte[] clearBytes = Encoding.Unicode.GetBytes(textToEncrypt);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
textToEncrypt = Convert.ToBase64String(ms.ToArray());
}
}
return textToEncrypt;
}
Decryption
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string username = Decrypt(HttpUtility.UrlDecode(Request.QueryString["name"]));
string userid = Decrypt(HttpUtility.UrlDecode(Request.QueryString["id"]));
}
}
private string Decrypt(string textToDecrypt)
{
string EncryptionKey = "Writeyourkeyhere-Youcanwriteanything";
textToDecrypt = textToDecrypt.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(textToDecrypt);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
textToDecrypt = Encoding.Unicode.GetString(ms.ToArray());
}
}
return textToDecrypt;
}
Hope this will help you and save your time.
Enjoy !!!
:)