Skip to content

Instantly share code, notes, and snippets.

@rcknr
Created August 28, 2018 07:37
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rcknr/47d3a175fb32647742850666dbdbc086 to your computer and use it in GitHub Desktop.
Save rcknr/47d3a175fb32647742850666dbdbc086 to your computer and use it in GitHub Desktop.
Laravel Custom Hasher

Laravel Custom Hasher

When you need to hash and check passwords using an algorithm other than supported bcrypt or argon there is an easy way to add a custom one. When I needed to use md5 for a legacy project I have tried to quickly google a solution and most I had found were based on creating a ServiceProvider which completely overrides builtin HashManager. The other way would be to extend it instead. So I have added a following into my AuthServiceProvider's boot() method:

$this->app->make('hash')->extend('md5', function() {
    return new Md5Hasher;
});

Then, created a hasher itself:

<?php

namespace App\Auth\Hashing;

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

class Md5Hasher extends AbstractHasher implements HasherContract
{

    /**
     * Hash the given value.
     *
     * @param  string $value
     * @param  array $options
     * @return string
     */
    public function make($value, array $options = [])
    {
        return md5($value);
    }

    /**
     * Check if the given hash has been hashed using the given options.
     *
     * @param  string $hashedValue
     * @param  array $options
     * @return bool
     */
    public function needsRehash($hashedValue, array $options = [])
    {
        return false;
    }

    /**
     * Check the given plain value against a hash.
     *
     * @param  string  $value
     * @param  string  $hashedValue
     * @param  array  $options
     * @return bool
     */
    public function check($value, $hashedValue, array $options = [])
    {
        return $this->make($value) === $hashedValue;
    }
}

And finally in config/hashing.php configuration file you can set your default driver:

'driver' => 'md5',

With this method you can still use other drivers with Hash facade:

$hash_default = Hash::make('test'); // Uses default driver
$hash_bcrypt = Hash::driver('bcrypt')->make('test'); // Uses 'bcrypt' driver
@asadbek-fayzulloev
Copy link

Hello friend, thanks for your help!

@asadbek-fayzulloev
Copy link

I did same, but there is Error (Call to undefined method App\Service\Hasher\Md5Hasher::extend()). How can I fix this issue?

@rcknr
Copy link
Author

rcknr commented Jan 31, 2022

@Asadbekinha You probably have a typo. You have to call extend on either Hash facade or like is shown above.

@adrianoleiterodrigues
Copy link

works like a charm! thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment