locked
How to do the URL encryption/decryption C#? RRS feed

  • Question

  • User-1148373670 posted

    Hi All,

    I want to do the URL encryption across the application. Please provide some common method to implement the URL encryption/Decryption in C#. How to generate the encryption key randomly for particular session to use for encryption and decryption.

    As of now I am generation random encryption key using below code

    private static Random random = new Random();
    public static string RandomString(int length)
    {
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return new string(Enumerable.Repeat(chars, length)
    .Select(s => s[random.Next(s.Length)]).ToArray());
    }

    I am not able to keep the key for particular session. Please sombody provide the input on it ASAP.

    Thanks in advance

    Ambrish

    Friday, October 7, 2016 6:37 AM

Answers

  • User-707554951 posted

    Hi info2ambrish,
    From your description, I suggest you could encrypt QueryString Parameter values using AES Algorithm  and pass it to another page;
    The following  is an example, you could refer to it :
    Page 1:

    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                Name:
            </td>
            <td>
                <asp:TextBox ID="txtName" runat="server" Text="Mudassar Khan" />
            </td>
        </tr>
        <tr>
            <td>
                Technology:
            </td>
            <td>
                <asp:DropDownList ID = "ddlTechnology" runat="server">
                    <asp:ListItem Text="ASP.Net" Value = "ASP.Net" />
                    <asp:ListItem Text="PHP" Value = "PHP" />
                    <asp:ListItem Text="JSP" Value = "JSP" />
                </asp:DropDownList>
            </td>
        </tr>
    </table>
    <hr />
    <asp:Button ID="Button1" Text="Submit" runat="server" OnClick = "Submit" />
    
    

    Codebehind:

    using System.IO;
    using System.Text;
    using System.Security.Cryptography;
    protected void Submit(object sender, EventArgs e)
    {
        string name = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()));
        string technology = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value));
        Response.Redirect(string.Format("~/CS2.aspx?name={0}&technology={1}", name, technology));
    }
     
    private string Encrypt(string clearText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        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();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }

    Page 2:

    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                Name:
            </td>
            <td>
                <asp:Label ID="lblName" runat="server" Text="" />
            </td>
        </tr>
        <tr>
            <td>
                Technology:
            </td>
            <td>
                <asp:Label ID="lblTechnology" runat="server" Text="" />
            </td>
        </tr>
    </table>
    
    

    CodeBehind:

    using System.IO;
    using System.Text;
    using System.Security.Cryptography;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString["name"]));
            lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString["technology"]));
        }
    }
     
    private string Decrypt(string cipherText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        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();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }

    Best regards
    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 7, 2016 12:39 PM
  • User-471420332 posted

    Dear info2ambrish,

                        Below is best working example, you can follow.

    http://www.aspsnippets.com/Articles/Encrypt-and-Decrypt-QueryString-Parameter-Values-in-ASPNet-using-C-and-VBNet.aspx

    Thank you

    Mazhar

    Mark as an answer If you get answer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 7, 2016 2:30 PM

All replies

  • User-644521530 posted

    You may pass a session relative integer to the function, then you may have that.

    Friday, October 7, 2016 10:33 AM
  • User-1148373670 posted

    Thanks for reply....

    I have created class that inheriting IHttpModule. Inside the class method not able to get the session assigned value. can u pls help me how to get the value in this class.

    public class MyClass : IHttpModule
    {

    void context_BeginRequest(object sender, EventArgs e)
    {

    //here i am not able to get the session value. Assigning the session value at click of login button.

    }

    }

    Thanks

    Friday, October 7, 2016 12:37 PM
  • User-707554951 posted

    Hi info2ambrish,
    From your description, I suggest you could encrypt QueryString Parameter values using AES Algorithm  and pass it to another page;
    The following  is an example, you could refer to it :
    Page 1:

    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                Name:
            </td>
            <td>
                <asp:TextBox ID="txtName" runat="server" Text="Mudassar Khan" />
            </td>
        </tr>
        <tr>
            <td>
                Technology:
            </td>
            <td>
                <asp:DropDownList ID = "ddlTechnology" runat="server">
                    <asp:ListItem Text="ASP.Net" Value = "ASP.Net" />
                    <asp:ListItem Text="PHP" Value = "PHP" />
                    <asp:ListItem Text="JSP" Value = "JSP" />
                </asp:DropDownList>
            </td>
        </tr>
    </table>
    <hr />
    <asp:Button ID="Button1" Text="Submit" runat="server" OnClick = "Submit" />
    
    

    Codebehind:

    using System.IO;
    using System.Text;
    using System.Security.Cryptography;
    protected void Submit(object sender, EventArgs e)
    {
        string name = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()));
        string technology = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value));
        Response.Redirect(string.Format("~/CS2.aspx?name={0}&technology={1}", name, technology));
    }
     
    private string Encrypt(string clearText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        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();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }

    Page 2:

    <table border="0" cellpadding="0" cellspacing="0">
        <tr>
            <td>
                Name:
            </td>
            <td>
                <asp:Label ID="lblName" runat="server" Text="" />
            </td>
        </tr>
        <tr>
            <td>
                Technology:
            </td>
            <td>
                <asp:Label ID="lblTechnology" runat="server" Text="" />
            </td>
        </tr>
    </table>
    
    

    CodeBehind:

    using System.IO;
    using System.Text;
    using System.Security.Cryptography;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString["name"]));
            lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString["technology"]));
        }
    }
     
    private string Decrypt(string cipherText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        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();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }

    Best regards
    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 7, 2016 12:39 PM
  • User-471420332 posted

    Dear info2ambrish,

                        Below is best working example, you can follow.

    http://www.aspsnippets.com/Articles/Encrypt-and-Decrypt-QueryString-Parameter-Values-in-ASPNet-using-C-and-VBNet.aspx

    Thank you

    Mazhar

    Mark as an answer If you get answer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 7, 2016 2:30 PM