Syed Yunus
Syed Yunus

Reputation: 308

How to store password in encrypted format in database entered from web application?

In my application there is a password field. When user enters password it should encrypt that password and store into database. When user login into that application then password should fetch from database and decryption should take place.

Is it possible??

Upvotes: 8

Views: 57001

Answers (7)

Code
Code

Reputation: 739

 string hashedPassword = Security.HashSHA1(txtPassword.Value.Trim());
  public class Security
    {
        public static string HashSHA1(string value)
        {
            var sha1 = System.Security.Cryptography.SHA1.Create();
            var inputBytes = Encoding.ASCII.GetBytes(value);
            var hash = sha1.ComputeHash(inputBytes);

            var sb = new StringBuilder();
            for (var i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }
    }

Upvotes: -1

user5076813
user5076813

Reputation: 11

The simple way to do this is as follows:

string hashedpassword= FormsAuthentication.HashPasswordForStoringInConfigFile("your password", "SHA1");

Upvotes: 1

Sabry
Sabry

Reputation: 135

If you do not wish to use the ASP.NET Membership and Role providers, this might be useful to you :

    /// <summary>
    /// Decrypts the specified encryption key.
    /// </summary>
    /// <param name="encryptionKey">The encryption key.</param>
    /// <param name="cipherString">The cipher string.</param>
    /// <param name="useHashing">if set to <c>true</c> [use hashing].</param>
    /// <returns>
    ///  The decrypted string based on the key
    /// </returns>
    public static string Decrypt(string encryptionKey, string cipherString, bool useHashing)
    {
        byte[] keyArray;
        //get the byte code of the string

        byte[] toEncryptArray = Convert.FromBase64String(cipherString);

        System.Configuration.AppSettingsReader settingsReader =
                                            new AppSettingsReader();

        if (useHashing)
        {
            //if hashing was used get the hash code with regards to your key
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
            //release any resource held by the MD5CryptoServiceProvider

            hashmd5.Clear();
        }
        else
        {
            //if hashing was not implemented get the byte code of the key
            keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);
        }

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)

        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(
                             toEncryptArray, 0, toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor
        tdes.Clear();
        //return the Clear decrypted TEXT
        return UTF8Encoding.UTF8.GetString(resultArray);
    }

    /// <summary>
    /// Encrypts the specified to encrypt.
    /// </summary>
    /// <param name="toEncrypt">To encrypt.</param>
    /// <param name="useHashing">if set to <c>true</c> [use hashing].</param>
    /// <returns>
    /// The encrypted string to be stored in the Database
    /// </returns>
    public static string Encrypt(string encryptionKey, string toEncrypt, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader =
                                            new AppSettingsReader();

        //If hashing use get hashcode regards to your key
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(encryptionKey));
            //Always release the resources and flush data
            // of the Cryptographic service provide. Best Practice

            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(encryptionKey);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)
        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)

        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        //transform the specified region of bytes array to resultArray
        byte[] resultArray =
          cTransform.TransformFinalBlock(toEncryptArray, 0,
          toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor
        tdes.Clear();
        //Return the encrypted data into unreadable string format
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

Using the two above methods you could encrypt the password string as it is being saved to the database and decrypt it on retrieval.

Upvotes: 3

JayOnDotNet
JayOnDotNet

Reputation: 398

The simplest way to get hash password is as follow. FormsAuthentication.HashPasswordForStoringInConfigFile("value of string", FormsAuthPasswordFormat.MD5.ToString());

Upvotes: 0

kuldeep verma
kuldeep verma

Reputation: 326

You can Create SQLCLR UDF in SQL SERVER , There are Two main Method I used to Save Password in Encrpted Format .

Pwdencryp()t encrypts a password, returning the encrypted string. This is used when you set a password, and the encrypted password is stored in the master..syslogins table.

http://msdn.microsoft.com/en-us/library/dd822791(v=sql.105).aspx

Pwdcompare() accepts a clear password and an encrypted one, and checks whether they match by encrypting the clear password and comparing the two. When you type your password to log into SQL Server, this routine is called.

http://msdn.microsoft.com/en-us/library/dd822792.aspx

Upvotes: 2

npinti
npinti

Reputation: 52185

You could take a look at this link which could get you started in the right direction.

That being said however, it is the usual practice to store the hash value of the password itself rather than an encrypted version of the password. The hashing will allow you to check if the user has entered the correct password (by comparing the hash value you have in your database with the hash value of whatever the user entered) without the need of knowing what is the actual password.

The advantage of this is that it is usually simpler and more secure since you do not need to encrypt/decrypt any values. The drawback of using hashing is that you can never send the users their passwords (if you are planning to provide some sort of 'forgot my password' functionality) but rather you will have to reset it to a new, random one.

Upvotes: 22

Chris Moutray
Chris Moutray

Reputation: 18349

ASP.NET SQL Server membership provider gives you this feature when you configure the passwordFormat="Hashed" ASP.NET password hashing and password salt

But it you're looking to roll your own then you'll want to research into Salted Password. For example Hash and salt passwords in C#

Upvotes: 1

Related Questions