Laravel Hash 密码安全性

Laravel Hash 密码安全性

辞职了在家没事研究下 Laravel 的源码,想看一下哈希如何生成,这样子好在其他非 Laravel 项目去兼容密码验证。

vendor\laravel\framework\src\Illuminate\Hashing\BcryptHasher.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Hash the given value.
*
* @param string $value
* @param array $options
* @return string
*
* @throws \RuntimeException
*/
public function make($value, array $options = [])
{
$hash = password_hash($value, PASSWORD_BCRYPT, [
'cost' => $this->cost($options),
]);

if ($hash === false) {
throw new RuntimeException('Bcrypt hashing not supported.');
}

return $hash;
}

结果发现并没有使用到 .env 那边的 APP_KEY。在被拖库的情况下密码会更容易被暴力破解处理。

目前的话加强强度我都是在前面加一个固定的盐值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;

class IndexController extends Controller
{
/**
* 获取哈希 key
* https://github.com/laravel/framework/blob/6.x/src/Illuminate/Auth/Passwords/PasswordBrokerManager.php#L85
*
* @return string
*/
protected function get_hash_key()
{
$key = config('app.key');

if (Str::startsWith($key, 'base64:')) {
$key = base64_decode(substr($key, 7));
}

return $key;
}

public function index()
{
$hash_key = $this->get_hash_key();

// 密码
$password_value = 'zLoppLPKravEgs9d';

// 哈希密码生成
$password_hash = Hash::make($hash_key . $password_value);

// 哈希密码验证
if(Hash::check($hash_key . $password_value, $password_hash)) {
// 验证成功
}
}
}
往上