How to change login hash bcrypt to hash256

Viewed 1170

I am trying to change hashing in the laravel. So I made custom SHA256 with salt in the RegisterController. Register completed but how to change in the login?

protected function create(array $data)
{
    $salt = Str::random(8);
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => '$SHA$' . $salt . '$' . hash('sha256', hash('sha256', $data['password']) . $salt),
    ]);
}

This is code of LoginController. $this->guard()->attempt($this->credentials($request)) this goes to something and hash then get token.

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Exceptions\VerifyEmailException;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    use AuthenticatesUsers;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Attempt to log the user into the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        $token = $this->guard()->attempt($this->credentials($request));

        if (! $token) {
            return false;
        }

        $user = $this->guard()->user();
        if ($user instanceof MustVerifyEmail && ! $user->hasVerifiedEmail()) {
            return false;
        }

        $this->guard()->setToken($token);

        return true;
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    protected function sendLoginResponse(Request $request)
    {
        $this->clearLoginAttempts($request);
        $user = $this->guard()->user();
        $token = (string) $this->guard()->getToken();
        $expiration = $this->guard()->getPayload()->get('exp');

        return response()->json([
            'token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $expiration - time(),
        ]);
    }

    /**
     * Get the failed login response instance.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        $user = $this->guard()->user();
        if ($user instanceof MustVerifyEmail && ! $user->hasVerifiedEmail()) {
            throw VerifyEmailException::forUser($user);
        }

        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);
    }

    /**
     * Log the user out of the application.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();
    }
}
2 Answers

Here is (what I believe is) the correct way to add hashing functions:

Step 1: Create your hasher by implementing the Hasher contract:

namespace App; 
use Illuminate\Contracts\Hashing\Hasher as HasherContract;

class Sha256Hasher implements HasherContract {
    public function make($value, array $options = []) {
           $salt = Str::random(8);
           return '$SHA$' . $salt . '$' . hash('sha256', hash('sha256', $data['password']) . $salt),
    }
    public function info($value) {
       // Implement something that works like https://www.php.net/manual/en/function.password-get-info.php
    } 

    public function check($value, $hashedValue, array $options = [])) {
        // Verify the hash here e.g.
        return $this->make($value, $options) === $hashedValue;
        // But more secure than this
    }

    public function needsRehash($hashedValue, array $options = []) {
          return <a boolean whether the passwords needs rehashing>;
    }

}

You can then extend the hashers with this hasher. In a service provider add:

     Hash::extend('sha256', function () {
         return new Sha256Hasher();
     });

Then (finally) change your default hashing driver in your config/hashing.php:

'driver' => 'sha256',

This should switch your hashing to use your new driver and should not need any changes to views or models.

First, create this function where you can reuse it:

protected function hash($string){
    return hash('sha256', $string . config('app.encryption_key'));
}

On user creation you have to call the function to hash the password:

protected function create(array $data){
    return User::create([
       'name' => $data['name'],
       'password' => $this->hash($data['password'])
    ]);
}

On login, you would have to call hash function on password again:

protected function login(Request $request){
    $user = User::where([
           'email' => $request->request('email'), 
           'password' => $this->hash($request->input('password')) 
    ])->first();
    Auth::login($user);
    $token = $user->createToken('MyApp')->accessToken;
    return response()->json(compact('token', 'user'));
}

I think that is the best approach to consider.

Related