zl程序教程

您现在的位置是:首页 >  Java

当前栏目

laravel 中使用 Hash::make() 对用户密码进行加密

2023-02-18 16:47:45 时间

laravel 中使用 Hash::make() 对用户密码进行加密

问题描述: 在调试中发现使用 Hash:make($password) 对用户密码进行加密;在验证时发现对于相同的password 会出现不同的加密结果,那么加密之后进行对比肯定是不相等的。

看了下实现方式: 使用Hash::check($password,$userInfo->password)

这种方式来对密码进行校验,不能使用Hash:make($password) == $userInfo->password来进行判断。

先关代码如下:

<?php

namespace Illuminate\Support\Facades;

/**
 * @method static array info(string $hashedValue)
 * @method static bool check(string $value, string $hashedValue, array $options = [])
 * @method static bool needsRehash(string $hashedValue, array $options = [])
 * @method static string make(string $value, array $options = [])
 *
 * @see \Illuminate\Hashing\HashManager
 */
class Hash extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'hash';
    }
}

看了下源码,发现该方法是使用 PHP 内置函数 password_hash() 来进行加密的。为什么使用 password_hash() 而不是用 md5() 呢?

因为 password_hash() 每次加密的结果都不相同,调用该方法会产生随机的 salt 值,这样加密后不容易产生碰撞,破解原始密码。那么password_verify() 是怎么检测密码是不是相等的呢,该加密过程是单向的,不可能是通过解密拿到原始密码来进行判断。(这样不符合安全规则,加密方式只能是单向的)。查看加密后的字符串,会发现有几个$,这就相当于定界符,字符串中包含了版本号,递归层数,salt 的值,知道这几个就可以通过相同的值来进行加密,然后进行判断。因为 salt 和递归层数都相同,所以加密后的值也是相同的。