Post

Encrypting and Decrypting Query Strings in asp.net

Introduction

We often pass values between pages in the form of a query string as key-value pairs. Query string is the easiest way and most widely practiced mechanism of transferring small pieces of data between web pages. The end-user may change the value in the query string to play around with the application, and at the same time, it leads to compromising the security and data integrity of the system. So the solution is encrypting the query strings.

Following is the simple way of encryption and decryption mechanism in asp.net

First I created two methods for encryption and decryption

Encrypt the string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private string Encrypt(string stringToEncrypt)
{
    byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
    byte[] rgbIV = { 0x21, 0x43, 0x56, 0x87, 0x10, 0xfd, 0xea, 0x1c };
    byte[] key = { };
    try
    {
        key = System.Text.Encoding.UTF8.GetBytes("A0D1nX0Q");
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }
    catch (Exception e)
    {
        return e.Message;
    }
}

Decrypt the encrypted string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private string Decrypt(string EncryptedText)
{
    byte[] inputByteArray = new byte[EncryptedText.Length + 1];
    byte[] rgbIV = { 0x21, 0x43, 0x56, 0x87, 0x10, 0xfd, 0xea, 0x1c };
    byte[] key = { };
    
    try
    {
        key = System.Text.Encoding.UTF8.GetBytes("A0D1nX0Q");
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByteArray = Convert.FromBase64String(EncryptedText);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        return encoding.GetString(ms.ToArray());
    }
    catch (Exception e)
    {
        return e.Message;
    }
}
This post is licensed under CC BY 4.0 by the author.