Laravel 使用 MD5 作为密码 hash 算法

公司内部旧系统使用的 MD5 做密码,只好改了下密码验证方式。

创建新文件 MD5Hasher.php

  • app/Hashing/Md5Hasher.php
<?php

namespace App\Hashing;

use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Hashing\AbstractHasher;

class Md5Hasher extends AbstractHasher implements HasherContract
{
    public function make($value, array $options = []): string
    {
        return md5($value);
    }

    public function check($value, $hashedValue, array $options = []): bool
    {
        return $this->make($value) == $hashedValue;
    }

    public function needsRehash($hashedValue, array $options = []): bool
    {
        return false;
    }
}

在 ServiceProvider 里注册新 hash

  • app/Providers/AppServiceProvider.php
<?php

namespace App\Providers;

use App\Hashing\Md5Hasher;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // use md5 as password hash
        $this->app->make('hash')->extend('md5', function () {
            return new Md5Hasher();
        });
    }
}

修改默认的 hash driver

  • config/hashing.php
    //...
    'driver' => 'md5',  // 'driver' => 'bcrypt',
    //...