Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 984
Hemant Kothiyal Avatar asked Jul 13 '10 10:07

Hemant Kothiyal


1 Answers

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...
}
like image 156
Simon Mourier Avatar answered Oct 12 '22 00:10

Simon Mourier