Mar
24
2013

Simple way to encrypt and decrypt password or data in ASP.NET C#

For the security reasons that you wanted to encypt your password or sensitive data before storing it to the database and decypt after pulling it from the database using ASP.NET C#.

Here is two simple method on how to encrypt and decrypt password:

 

In the code behind (aspx.cs) page, use the following code:

 

/// <summary>
        /// To encrypt the input password
        /// </summary>
        /// <param name="txtPassword"></param>
        /// <returns>It returns encrypted code</returns>
        public string EncryptPassword(string txtPassword)
        {     
            byte[] passBytes = System.Text.Encoding.Unicode.GetBytes(txtPassword);
            string encryptPassword = Convert.ToBase64String(passBytes);
            return encryptPassword;
        }


        /// <summary>
        /// To Decrypt password
        /// </summary>
        /// <param name="encryptedPassword"></param>
        /// <returns>It returns plain password</returns>
        public string DecryptPassword(string encryptedPassword)
        {
            byte[] passByteData = Convert.FromBase64String(encryptedPassword);
            string originalPassword = System.Text.Encoding.Unicode.GetString(passByteData);
            return originalPassword;
        }

 

As you see the source code above, you would call the EncryptPassword(string txtPassword) method passing user input password in parameter to encrypt the password, from there you can save the encrypted password to the database.

 

When you need to decode the encrypted password, you would call the DecryptPassword(string encryptedPassword) method which passing the encrypted password in parameter to return the original password.

 

That's it. Have fun and good luck!

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Calendar

<<  October 2020  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar