.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> ASP.NET Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

code for encrypting and de-crypting the password

Posted By:Athira Sreejith       Posted Date: January 02, 2009    Points: 10    Category: ASP.NET Controls    URL: http://www.dotnetspark.com  
 

------------------------------
CODE FOR PASSWORD ENCRYPTION:
------------------------------

public string Encrypt(string toEncrypt, string key)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
string resultbase64String = Convert.ToBase64String(resultArray, 0, resultArray.Length);
string resultEncodedString = HttpUtility.UrlEncode(resultbase64String);
return resultEncodedString;
}

-------------------------------
CODE FOR PASSWORD DECRYPTION:
-------------------------------
public string Decrypt(string cipherString, string key)
{
try
{
byte[] keyArray;
string cipherDecodedString = HttpUtility.UrlDecode(cipherString);
//TODO: The encoding from + to " " and decoding isnt very clear
//Find out the exact characterset and then use them.
byte[] toEncryptArray = Convert.FromBase64String((cipherDecodedString.Replace(' ', '+')));


MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

tdes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
catch (Exception ex)
{
return "";
}
}



     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend