How to use SHA1 encryption instead of BCrypt in Laravel 4?

You’ll have to rewrite the Hash module. Thanks to Laravel’s ideas of following IoC and Dependency Injection concepts, it’ll be relatively easy.

First, create a app/libraries folder and add it to composer’s autoload.classmap:

"autoload": {
    "classmap": [
        // ...

        "app/libraries"
    ]
},

Now, it’s time we create our class. Create a SHAHasher class, implementing Illuminate\Hashing\HasherInterface. We’ll need to implement its 3 methods: make, check and needsRehash.

Note: On Laravel 5, implement Illuminate/Contracts/Hashing/Hasher instead of Illuminate\Hashing\HasherInterface.

app/libraries/SHAHasher.php

class SHAHasher implements Illuminate\Hashing\HasherInterface {

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

    /**
     * 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 = array()) {
        return $this->make($value) === $hashedValue;
    }

    /**
     * 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 = array()) {
        return false;
    }

}

Now that we have our class done, we want it to be used by default, by Laravel. To do so, we’ll create SHAHashServiceProvider, extending Illuminate\Support\ServiceProvider, and register it as the hash component:

app/libraries/SHAHashServiceProvider.php

class SHAHashServiceProvider extends Illuminate\Support\ServiceProvider {

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register() {
        $this->app['hash'] = $this->app->share(function () {
            return new SHAHasher();
        });

    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides() {
        return array('hash');
    }

}

Cool, now all we have to do is make sure our app loads the correct service provider. On app/config/app.php, under providers, remove the following line:

'Illuminate\Hashing\HashServiceProvider',

Then, add this one:

'SHAHashServiceProvider',

Leave a Comment