Use Salt + Hash to encrypt passwords and store them in database _ Practical Tips

Source: Internet
Author: User

(a) Why do I use hash functions to encrypt passwords

If you need to save a password (such as a website user's password), you should consider how to protect the password data, and it is extremely unsafe to write the password directly to the database as follows, because anyone who can open the database will be able to see the passwords directly.

The solution is to encrypt the password and then store it in the database, the more commonly used encryption method is to use the hash function (hash functions). The specific definition of a hash function can be found on the Internet or in related books, simply speaking, its characteristics are as follows:

(1) The original password is computed by a hash function and a hash value is obtained.

(2) Change the original password, the hash function to calculate the hash value will be changed accordingly

(3) The same password, the hash value is the same

(4) The hash function is one-way and irreversible. In other words, from the hash value, you can't figure out what the original password is.

With the hash function, we can store the hash value of the password in the database. When a user logs on to the site, we can verify that the hash value of the user's password is the same as the hash value in the database.

Because the hash function is irreversible, even if someone opens the database, you cannot see how much the user's password is.

Is it safe to store passwords that are encrypted with a hash function? Let's take a look at some common ways to crack passwords.

(b) Several common methods of deciphering passwords

The simplest and most common way to crack is in dictionary cracking (Dictionary Attack) and brute force cracking (brute Force Attack). Both of these methods are simply guessing the password.

Dictionary cracking and brute force cracking are less efficient ways to crack. If you know the hash value of the password in the database, you can use a more efficient way of cracking, look-up table (Lookup tables). Other methods, such as the Reverse lookup table (Reverse Lookup tables), the Rainbow table (Rainbow tables), and so on, are similar to the Look-up table method. Now let's look at the principle of the look-up table method.

The tabular method does not guess the password like dictionary crack and brute force crack, it first calculates the hash value of some more commonly used passwords, and then builds a table, of course the more the password, the larger the table. When you know the hash value of a password, you only need to look up the hash value in the table you've built, and if you do, you know the corresponding password.

(iii) Add salt to the password (salted)

From the above tabular method, it is not safe to store the hash value of the original cipher in the database even though it is encrypted. So what is the best way to solve this problem? The answer is to add salt.

What is salt? is a randomly generated string. We combine the salt with the original password (concat) (either at the front or back), and then encrypt the concat string. By encrypting the password in this way, the look-up table method doesn't work (because salt is randomly generated).

(iv) implementation in. Net

In. NET, you can use the RNGCryptoServiceProvider class to generate salt, and of course you can use GUIDs. hash function algorithm We can use the SHA (Secure hash algorithm) family algorithm, of course, there are many hash function algorithms, such as you can also use MD5. By the way, the United States government used to widely use the SHA-1 algorithm, in 2005 by China's Shandong University professor Wangxiaoyun found a security loophole, so now more commonly used SHA-1 lengthened variants, such as SHA-256. In. NET, you can use the SHA256Managed class.

Let's look at a piece of code that shows how to. NET to add salt encryption to the password. The encrypted password is stored in the MySQL database.

The following code shows how to register a new account. Salt can be generated using a new GUID, or you can use the RNGCryptoServiceProvider class. Convert byte[] to string, you can use base64string (I have described the base Encoding encoding in my previous blog), or I can use the following tohexstring method.

Copy Code code as follows:

protected void Buttonregister_click (object sender, EventArgs e)
{
string username = Textboxusername.text;
string password = Textboxpassword.text;
Random salt
string salt = Guid.NewGuid (). ToString ();

Random salt
can also use RNGCryptoServiceProvider class
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider ();
byte[] saltbytes = new BYTE[36];
Rng. GetBytes (saltbytes);
string salt = convert.tobase64string (saltbytes);
string salt = tohexstring (saltbytes);

byte[] passwordandsaltbytes = System.Text.Encoding.UTF8.GetBytes (password + salt);
byte[] hashbytes = new System.Security.Cryptography.SHA256Managed (). ComputeHash (passwordandsaltbytes);

String hashstring = Convert.tobase64string (hashbytes);

can also use tohexstring to convert byte[] to string
String hashstring = Tohexstring (hashbytes);

var db = new Testentities ();
Usercredential NewRecord = usercredential. Createusercredential (username, hashstring, salt);
Db.usercredentials.AddObject (NewRecord);
Db. SaveChanges ();
}

String tohexstring (byte[] bytes)
{
var hex = new StringBuilder ();
foreach (Byte b in bytes)
{
Hex. AppendFormat ("{0:x2}", b);
}
Return hex. ToString ();
}



The following code shows how to verify that the password for the logged-on user is correct. First verify that the user name exists, and if so, obtain the user's salt, and then compute the hash value with the salt and the user-entered password, and compare it with the hash value in the database.
Copy Code code as follows:

protected void Buttonsignin_click (object sender, EventArgs e)
{
string username = Textboxusername.text;
string password = Textboxpassword.text;

var db = new Testentities ();
Usercredential record = Db.usercredentials.Where (x => string.compare (X.username, UserName, true) = = 0). FirstOrDefault ();
if (record = = Default (usercredential))
{
throw new ApplicationException ("Invalid user name and password");
}

string salt = record. Salt;
byte[] passwordandsaltbytes = System.Text.Encoding.UTF8.GetBytes (password + salt);
byte[] hashbytes = new System.Security.Cryptography.SHA256Managed (). ComputeHash (passwordandsaltbytes);
String hashstring = Convert.tobase64string (hashbytes);

if (hashstring = = record. PasswordHash)
{
User Login successfully
}
Else
{
throw new ApplicationException ("Invalid user name and password");
}
}

Summary: Using only hash functions to encrypt passwords is not enough, you need to add salt to the password to improve security, the length of salt can not be too short, and the production of salt should be random.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.