Thursday, December 18, 2014

Password Encryption and Decryption in ASP.NET

secure_passwords 
  1.  This Method illustrates the Password Encryption...
public static string Encrypt(string originalString)
{
      if (originalString == null)
      {
            return originalString = “”;
      }
      if (String.IsNullOrEmpty(originalString))
      {
            throw new ArgumentNullException
            (“The string which needs to be encrypted can not be null.”);
      }
      DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
      MemoryStream memoryStream = new MemoryStream();
      CryptoStream cryptoStream = new CryptoStream(memoryStream,
      cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
      StreamWriter writer = new StreamWriter(cryptoStream);
      writer.Write(originalString);
      writer.Flush();
      cryptoStream.FlushFinalBlock();
      writer.Flush();
      return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
Now, You can call this mehod as ClassName.Encrypt("Your Password");

  2. This Method illustrates the Password Decryption...
public static string Decrypt(string cryptedString)
{
      if (String.IsNullOrEmpty(cryptedString))
      {
            throw new ArgumentNullException
            (“The string which needs to be decrypted can not be null.”);
      }
      DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
      MemoryStream memoryStream = new MemoryStream
      (Convert.FromBase64String(cryptedString));
      CryptoStream cryptoStream = new CryptoStream(memoryStream,
      cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
      StreamReader reader = new StreamReader(cryptoStream);
      return reader.ReadToEnd();

Now, You can call this mehod as ClassName.Decrypt("Your Encrypted Password")

Note :  for that you have to add namespace of System.Security.Cryptography as like, 
 using System.Security.Cryptography;  


0 comments:

Post a Comment