11

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?

Krunal
  • 3,443
  • 3
  • 23
  • 27
Hemant Kothiyal
  • 4,092
  • 19
  • 61
  • 80
  • You don't need to call an external application. Use the cryptography API inside the framework to encrypt/decrypt data. http://msdn.microsoft.com/en-us/library/system.security.cryptography(VS.71).aspx – onof Jul 13 '10 at 10:14
  • Here's how I approached this task: http://blackbeltcoder.com/Articles/asp/encrypting-query-arguments. – Jonathan Wood Dec 19 '10 at 16:48
  • This is all built into ASP.NET -- no need to write your own crypto: http://brockallen.com/2012/06/21/use-the-machinekey-api-to-protect-values-in-asp-net/ – Brock Allen Nov 22 '12 at 15:37

1 Answers1

7

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...
}
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298