We know that if the password is hashed directly, hackers can obtain the hash value of the password, and then query the hash value Dictionary (for example, MD5 password cracking website ), obtain the password of a user.
Add salt can solve this problem to some extent. The so-called add salt method is to add some "condiments ". The basic idea is as follows: when a user provides a password for the first time (usually during registration), the system automatically adds "condiments" to the password and then hashes it. When a user logs on, the system providesCodeSprinkle the same "seasoning" with it, hash it, and then compare the hash value, and check whether the password is correct.
The "seasoning" here is called the "salt value", which is randomly generated by the system and only known by the system. In this way, even if two users use the same password, because the salt value generated by the system for them is different, their hash value is also different. Even if hackers can use their own passwords and their own hash values to find users with specific passwords, the probability is too small (the passwords and salt values must be the same as those used by hackers ).
The following example uses PHP to illustrate the MD5 ($ pass. $ salt) encryption function.
<? PHP
Function Hash ($ ){
$ Salt= "Random_kugbjvy ";// Define a salt value,ProgramSpecified random string
$ B = $ A. $ salt;// Connect the password to Salt
$ B = MD5 ($ B );// Execute MD5 Hash
Return $ B;// Returns the hash.
}
?>
Call method:$ New_password=Hash($ _ Post [Password]);// Here, accept the form submission value and encrypt it
The following describes the process of adding a salt hash. I would like to emphasize one point before the introduction. As mentioned above, the "same" seasoning should be used when the password is verified and the original hash password is used. Therefore, the salt value is stored in the database.
When a user registers,
- The user enters the [account] and [Password] (and other user information );
- The system generates a [salt value] for the user ];
- The system connects the salt value and the user password;
- Hash the connected values to obtain the [hash value ];
- Set 【Hash Value 1] And [salt value] are placed in the database respectively.
When a user logs on,
- Enter the account and password ];
- The system finds the corresponding [hash value] and [salt value] through the user name ];
- The system connects the salt value and the password entered by the user;
- Hash the connected values 【Hash Value 2] (Note the values calculated in real time );
- Compare [Hash Value1And [Hash Value2The password is correct. Otherwise, the password is incorrect.
Sometimes, to reduce the development pressure, programmers will use a single salt value (stored somewhere) instead of generating private salt values for each user.