Laravel 5.2 Default password encryption, how to add salt?
By the way weakly weak ask: what is salt?
protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); }
Reply content:
Laravel 5.2 Default password encryption, how to add salt?
By the way weakly weak ask: what is salt?
protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); }
Bcrypt generated a cipher hash that already contains salt.
Salt is a random string used to prevent the detection of passwords from rainbow tables
No salt situation: The user password is 123456, silly programmers directly in the database to save hash (' 123456 '), the bad guys get the database can be directly from the hash to detect the password
There is salt situation: the user still uses 123456, the normal programmer saves hash in the database (' 123456 ' + salt) and salt . Bad guys get the database and it's hard to restore the password from this hash (brute force is still possible, but at least the low-cost Rainbow watch is wasted)
https://github.com/laravel/framework/blob/5.1/src/Illuminate/Hashing/BcryptHasher.php
View this section of the source code available,
// Laravel 的 bcrypt 就是 $hash = password_hash($value, PASSWORD_BCRYPT, ['cost' => 10]);
Because Password_hash uses the crypt algorithm, it participates in the calculation of the hash value:
Algorithm (as the identity of the beginning of the ID can know the province, determined by the salt value of the format), cost (the default 10) and the salt value can be directly seen in the $hash!
So, the salt value of bcrypt in Laravel is PHP automatically randomly generated characters, although the same password every time the hash is not the same.
But through $hash and password, but can verify the correctness of the password!
Specifically, for example, this
$hash = password_hash('password',PASSWORD_BCRYPT,['cost' => 10]);echo $hash;// 比如我这次算的是// $hash = '$2y$10$DyAJOutGjURG9xyKgAaCtOm4K1yezvgNkxHf6PhuLYBCENk61bePm';
So we can see from the hash value of this crypt,
Because it starts with $2y$, its algorithm is crypt_blowfish.
At the same time the crypt_blowfish algorithm salt value format provisions are:
Start with $2y$ + a two-bit cost parameter + $ + 22-bit random character ("./0-9a-za-z")
$hash (Crypt_blowfish is fixed 60-bit) = Salt value + 31-bit one-way encrypted value
See also: https://secure.php.net/manual/en/function.crypt.php
Verify Password
if (password_verify('password', $hash)) { echo '密码正确.';} else { echo '密码错误!';}// 原理是: if ($hash === crypt('password', '$2y$10$DyAJOutGjURG9xyKgAaCtO')) { echo '密码正确.';} else { echo '密码错误!';}
If you write your own user system and use php5.5+ or PHP7, you can consider using PHP's own Password_hash () and password_verify (), very convenient