How can i encrypt query string parameters in ASP.NET website?

17,086

A good way of encrypting and decrypting string in the ASP.NET context is to use the FormsAuthentication.Encrypt Method

It seems to be only suited for cookie, but it works well in other context, plus, you can add an expiration date as well (or DateTime.MaxValue if it's not needed), this is a sample code:

public static string Encrypt(string content, DateTime expiration)
{
    return FormsAuthentication.Encrypt(new FormsAuthenticationTicket(1,
        HttpContext.Current.Request.UserHostAddress, // or something fixed if you don't want to stick with the user's IP Address
        DateTime.Now, expiration, false, content));
}

public static string Decrypt(string encryptedContent)
{
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encryptedContent);
    if (!ticket.Expired)
            return ticket.UserData;

    return null; // or throw...
}
Share:
17,086

Related videos on Youtube

Hemant Kothiyal
Author by

Hemant Kothiyal

Trying to find best value of "n" from n number of solutions

Updated on April 27, 2022

Comments

  • Hemant Kothiyal
    Hemant Kothiyal about 2 years

    In one of my ASP.Net websites, I have to provide a link to the user in which all query string parameters should be encrypted.

    What I am thinking is to use the command "aspnet_regiis" (as used to encrypt web.config data), pass output as a query string inside published url.

    When the user clicks that link, I first decrypt the string and then fetch the original data for the query string.

    Am I right in doing this? Is there any good technique to encrypt and decrypt query strings?