Adsence750x90

Monday, April 12, 2010

Encrypt and Decrypt String ASP.NET

You can Encrypt and Decrypt string  variable like QueryString etc by FormsAuthentication class. This class is Derived from System.Web.Security. This is a simple method to encryption and decryption. I think the code will definitely explain how it works. if anyone want detailed description just drop a comment i will reply ASAP.

First Initializes a new instance of  FormsAuthenticationTicket class, this ticket is used to encrypt via FormsAuthentication.Encrypt(FormsAuthenticationTicket tk) method. FormsAuthentication.Encrypt method return encrypted string.


FormsAuthenticationTicket has three parameters.parameters are  string name, bool isPersistent, and int timeout.The time, in minutes, for which the authentication ticket is valid. if isPersistent is true if the ticket will be stored in a persistent cookie (saved across browser sessions); otherwise, false. If the ticket is stored in the URL, this value is ignored.

Encrypt Method 

    private string Encrypt(string stringToEncrypt)
    {
        FormsAuthenticationTicket tk = new FormsAuthenticationTicket(stringToEncrypt, false, 600);
        // returns encrypted string
        return FormsAuthentication.Encrypt(tk);
    }

Decrypt Method

    private string Decrypt(string encryptedString)
    {
        FormsAuthenticationTicket tk= FormsAuthentication.Decrypt(encryptedString);
        return tk.Name;
    }

No comments: