8

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??

2
  • 1
    Before rolling your own code you might want to looking into ASP.NET membership and role providers, msdn.microsoft.com/en-us/library/yh26yfzy.aspx this is built into the framework and therefore page controls and other features of the framework integrate nicely with this May 22, 2012 at 5:56
  • 1
    Your question doesn't specify if you are trying to make a password login system, or just trying to store an encrypted string for other use. If you are looking for ways to encrypt a string so it can be decrypted later, then I suggest not mentioning the word "password" at all in your question, because it will lead to a lot of misunderstandings.
    – Deantwo
    Jan 29, 2019 at 14:34

7 Answers 7

22

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.

2
  • 1
    One cannot log in to, for example, an email server using the hash of the password. Hence there are legitimate needs for two way encryption.
    – Micah Epps
    Feb 6, 2018 at 14:34
  • @Micah Epps, then you are talking about storing a password for use elsewhere. It is not totally clear if that is what the original question is asking for or not. This answer correctly describe a method for password authentication, not encrypted string storing.
    – Deantwo
    Jan 29, 2019 at 14:32
3

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.

1
  • What is the purpose of variable settingsReader?
    – Micah Epps
    Feb 6, 2018 at 14:39
2

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

1
  • The name Pwdencrypt() looks bit misleading. It creates hash of the password in place of encrypting it. Hashing and encryption aren't same.
    – RBT
    Feb 10, 2022 at 10:08
1

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#

1

The simple way to do this is as follows:

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

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

-1
 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();
        }
    }
1
  • SHA-1 should absolutely not be used for hashing passwords; it is nowhere near strong enough; this is actively harmful. SHA-1 is now officially broken. Nov 20, 2020 at 10:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.