In depth analysis of the principle of password plus salt

  • 2020-06-12 08:34:22
  • OfStack

We know that if the password is hashed directly, the hacker can obtain the password by obtaining the hash value and then obtain the password of a user by looking up the hash value dictionary (for example, MD5 password cracking website).

Adding Salt can solve this problem to a certain extent. The Salt method is to add "seasoning". The basic idea is this: When a user first provides a password (usually when registering), the system automatically sprinkles some "seasoning" into the password and hashes it. When the user logs in, the system sprinkles the same seasoning on the user-supplied code, hashes it, and compares the hash values to determine if the password is correct.

The "condiments" here are called "Salt values," which are randomly generated by the system and known only to the system. This way, even if two users use the same password, they will have different hash values due to the different salt values the system generates for them. Even if a hacker could find a user with a specific password by using his password and the hash value he generated, the chances are small (both the password and the salt value would have to be the same as the one used by the hacker).

Using the PHP example, the md5($pass.$salt) encryption function is shown below.


<?php
function hash($a) {
    $salt= " Random_KUGBJVY " ;  // define 1 a salt The value, specified by the programmer, is a random string 
    $b=$a.$salt;  // The password and salt The connection 
    $b=md5($b);  // perform MD5 hash 
    return $b;  // Returns the hash     
}
?>

$new_password=hash($_POST[password]); // The form submission values are accepted and encrypted

The process of adding Salt hash to 1 is described in detail below. Before I introduce you, I want to emphasize that you need to use the "same" seasoning for password validation as you used for the original hashing password. So the Salt value is stored in the database.

When a user registers,

User enters [account] and [password] (and other user information); The system generates [Salt value] for the user; The system will connect [Salt value] and [user password] to 1; Hash the connected values to get [Hash value]; Put [Hash value 1] and [Salt value] into the database.
When the user logs in,

The user enters [account] and [password]; The system finds the corresponding [Hash value] and [Salt value] through the user name; The system will connect [Salt value] and [password entered by the user] to 1; Hash the values after the connection to get [Hash value 2] (note the value calculated in real time); Compare whether [Hash value 1] and [Hash value 2] are equal, equal means the password is correct, otherwise, the password is wrong.
Sometimes, to alleviate development stress, programmers will use one salt value (stored somewhere) for unified 1 instead of each user generating a private salt value.


Related articles: