Tuesday, May 25, 2010

Encrypt / Decrypt Password

hi
In asp.net the FormsAuthentication class provides an Encrypt method to create a string value that can be stored in a cookie or in the URL from a FormsAuthenticationTicket. The FormsAuthentication class also provides a Decrypt method to create a FormsAuthenticationTicket object from the encrypted authentication ticket retrieved from the forms-authentication cookie or the URL.

this is the sample code to create cookie with encrypt data

create ticket
FormsAuthenticationTicket t = new FormsAuthenticationTicket(1,username,Datetime.Now,Datetime.Now.Adddays(1),true, userdata,FormsAuthentication.FormsCookiePath );
1-- version
Datetime.Now -- created Date
Datetime.Now -- expireDate
true -- isPersistent cookie
userdata -- which data want encrypt
FormsAuthentication.FormsCookiePath -- path of the cookie

//encrypt method

string Encrypt = FormsAuthentication.Encrypt(t);
response.cookie.add(new Httpcookie(nameofcookie,Encrypt));


Sample code for Decrypt
if(request.cookie[nameofcookie] != null)
{
var cookie_ = request.cookie[nameofcookie];
FormsAuthenticationTicket t = FormsAuthentication.Decrypt(cookie_.value);
string s = t.userdata;

}