128

I am trying to create an hashed password for Laravel. Now someone told me to use Laravel hash helper but I can't seem to find it or I'm looking in the wrong direction.

How do I create a laravel hashed password? And where?

Edit: I know what the code is but I don't know where and how to use it so it gives me back the hashed password. If I get the hashed password then I can manually insert it into the database

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225
Graham
  • 1,850
  • 4
  • 21
  • 41
  • 1
    Check how to [make Hash and Verify Hash](http://stackoverflow.com/a/33740080/1045444) in Laravel. – Somnath Muluk Nov 16 '15 at 16:28
  • 8
    For those of you who are here to just manually create a hashed password, you can use the answer below with `php artisan tinker`. E.g., `echo Hash::make('yourpassword')` – sinaza Jul 22 '18 at 23:06
  • The quickest manual method which is helpful in the command line environment: `php artisan tinker` then `bcrypt("yourpassword")` – panjeh May 10 '23 at 20:06

16 Answers16

233

Hashing A Password Using Bcrypt in Laravel:

$password = Hash::make('yourpassword');

This will create a hashed password. You may use it in your controller or even in a model, for example, if a user submits a password using a form to your controller using POST method then you may hash it using something like this:

$password = Input::get('passwordformfield'); // password is form field
$hashed = Hash::make($password);

Here, $hashed will contain the hashed password. Basically, you'll do it when creating/registering a new user, so, for example, if a user submits details such as, name, email, username and password etc using a form, then before you insert the data into database, you'll hash the password after validating the data. For more information, read the documentation.

Update:

$password = 'JohnDoe';
$hashedPassword = Hash::make($password);
echo $hashedPassword; // $2y$10$jSAr/RwmjhwioDlJErOk9OQEO7huLz9O6Iuf/udyGbHPiTNuB3Iuy

So, you'll insert the $hashedPassword into database. Hope, it's clear now and if still you are confused then i suggest you to read some tutorials, watch some screen casts on laracasts.com and tutsplus.com and also read a book on Laravel, this is a free ebook, you may download it.

Update: Since OP wants to manually encrypt password using Laravel Hash without any class or form so this is an alternative way using artisan tinker from command prompt:

  1. Go to your command prompt/terminal
  2. Navigate to the Laravel installation (your project's root directory)
  3. Use cd <directory name> and press enter from command prompt/terminal
  4. Then write php artisan tinker and press enter
  5. Then write echo Hash::make('somestring');
  6. You'll get a hashed password on the console, copy it and then do whatever you want to do.

Update (Laravel 5.x):

// Also one can use bcrypt
$password = bcrypt('JohnDoe');

Adi Bnaya
  • 473
  • 4
  • 14
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • But where should i do this. I came across this a few times. – Graham Apr 03 '14 at 19:21
  • 1
    I think i made a wrong question. My database(which i got from someone else) has only hashed passwords for users. Now i want to create an password which should be hashed by laravel. How can i create an hashed password so i can enter this in the db. – Graham Apr 03 '14 at 19:38
  • That is what I've answered, to save a password into `db` you need to encrypt it so, from a plain password you'll encrypt it using `Hash::make('passwordstring');` and then save this hashed password in the database. – The Alpha Apr 03 '14 at 19:42
  • But how do i do this? If i just for example create a php file this doesn't work. As you'll understand i'm quite new to laravel – Graham Apr 03 '14 at 19:58
  • I think i still have a misleading question. Because I understand what you are saying. But where should I use this code? In which file or ... ? Because i'm only going to use this once. It's not for somekind of form that i can add a user or something. – Graham Apr 03 '14 at 20:42
  • Please describe what exactly you are going to do, in easy non-confusing words or phrases. – The Alpha Apr 03 '14 at 20:55
  • I have a table users where i can add another user. All the passwords are hashed by laravel. How can i get my password hashed so than i can enter it in my db. I know i must use Hash::make(myPassword) but how can i use it? I i just create a php file in my laravel project and run it it doesn't work. So where can i use it to get my password hashed – Graham Apr 03 '14 at 21:03
  • Do you want to manually hash passwords one by one and then you want to save each one manually in database ? – The Alpha Apr 03 '14 at 21:08
  • Yes. I just want to add 1 user and then manually add this in the database? or is this not possible? – Graham Apr 03 '14 at 21:17
  • What is your `OS`, anyways, check the updated answer. – The Alpha Apr 03 '14 at 21:19
  • Let me know the result soon, I'll leave now. – The Alpha Apr 03 '14 at 21:21
  • Thank you very much. This is what i needed. Would like to give a plus 1 but i don't have enough rep – Graham Apr 03 '14 at 21:39
  • You are welcome and it's `OK` I got the reputation from you because you said it and it's enough and +1 to your question as well :-) – The Alpha Apr 03 '14 at 21:42
  • For those of you using Laravel 5.0, for some reason, if you update the password using `php artisan tinker` approach, it automatically hashes it for you, so you need to do this: `> $u1->password = 'plaintextpassword'; $u1->save(); ` instead of `$u1->password = Hash::make('plaintextpassword'); $u1->save();`. I don't know why but that's the way it happens. Wasted a half hour wondering why my password changes didn't work. Turns out, they were pre-hashed. – racl101 May 18 '17 at 20:20
  • @TheAlpha hi sir, could you help me on this post? https://stackoverflow.com/questions/50771638/laravel-updateorcreate-on-onetoone-relationship Thanks – DolDurma Jun 09 '18 at 07:59
21

The Laravel Hash facade provides secure Bcrypt hashing for storing user passwords.

Basic usage required two things:

First include the Facade in your file

use Illuminate\Support\Facades\Hash;

and use Make Method to generate password.

$hashedPassword = Hash::make($request->newPassword);

and when you want to match the Hashed string you can use the below code:

Hash::check($request->newPasswordAtLogin, $hashedPassword)

You can learn more with the Laravel document link below for Hashing: https://laravel.com/docs/5.5/hashing

Prashant Barve
  • 4,105
  • 2
  • 33
  • 42
20

I know your pain bro. You just need the password Hash to replace the password column field in the database. You can get it easily from laravel tinker. On any laravel project command line type:

❯ php artisan tinker
Psy Shell v0.9.12 (PHP 7.4.27 — cli) by Justin Hileman
>>> echo Hash::make('123456');
$2y$10$JHK.2MTc9ORMmmlqoF.gg.SwDLnevVSj1oreHParu5PvcPEDOWqe6

then copy the hashed pass for your use case.

Zubayer Hossain
  • 428
  • 4
  • 8
19

Laravel 5 uses bcrypt. So, you can do this as well.

$hashedpassword = bcrypt('plaintextpassword');

output of which you can save to your database table's password field.

Fn Ref: bcrypt

Nagendra Rao
  • 7,016
  • 5
  • 54
  • 92
  • Where do you get this function from, it isn't part of PHP or Laravel is it? – martinstoeckli Aug 08 '15 at 13:38
  • 1
    @martinstoeckli Oh it is, it is a helper function in L5, http://laravel.com/docs/5.0/hashing#basic-usage – Nagendra Rao Aug 10 '15 at 12:29
  • Looks like it was introduced in the recent Laravel 5.1 http://laravel.com/docs/5.1/helpers#method-bcrypt – Nagendra Rao Aug 10 '15 at 12:35
  • How to decrypt this? IS there helper for this too? – Fusion Jul 05 '16 at 10:43
  • 2
    @Fusion bcrypt is a hashing algorithm, not an encryption algorithm, with hashing you can't get back the plain text once the hash is generated for it. This is the whole point of hashing algorithm. Only thing you can do is check if a plain text matches with the hash you have. – Nagendra Rao Jul 05 '16 at 10:51
  • @Fusion More on this, http://stackoverflow.com/a/18084693/1161412 Diff b/w the two: http://stackoverflow.com/a/4948393/1161412 – Nagendra Rao Jul 05 '16 at 11:01
  • thanks for answer, i just check in database like this ->where('password', '=',bcrypt($request->input('password'))) doesn't work – Freddy Sidauruk Mar 22 '17 at 04:31
  • 1
    @FreddySidauruk That won't work because bcrypt generates different hash every time, even if the input password is same. You will have to use the `check` method: `if (Hash::check('secret', $hashedPassword)) { // The passwords match... }` Ref: https://laravel.com/docs/5.1/hashing Edit: Don't forget to upvote the answer if it has helped you ;) – Nagendra Rao Mar 22 '17 at 13:52
10

If you want to understand how excatly laravel works you can review the complete class on Github: https://github.com/illuminate/hashing/blob/master/BcryptHasher.php

But basically there are Three PHP methods involved on that:

$pasword = 'user-password';
// To create a valid password out of laravel Try out!
$cost=10; // Default cost
$password = password_hash($pasword, PASSWORD_BCRYPT, ['cost' => $cost]);

// To validate the password you can use
$hash = '$2y$10$NhRNj6QF.Bo6ePSRsClYD.4zHFyoQr/WOdcESjIuRsluN1DvzqSHm';

if (password_verify($pasword, $hash)) {
   echo 'Password is valid!';
} else {
   echo 'Invalid password.';
}

//Finally if you have a $hash but you want to know the information about that hash. 
print_r( password_get_info( $password_hash ));

The hashed password is same as laravel 5.x bcrypt password. No need to give salt and cost, it will take its default values.

Those methods has been implemented in the laravel class, but if you want to learn more please review the official documentation: http://php.net/manual/en/function.password-hash.php

Jathin Prasad
  • 119
  • 1
  • 4
9

To store password in database, make hash of password and then save.

$password = Input::get('password_from_user'); 
$hashed = Hash::make($password); // save $hashed value

To verify password, get password stored of account from database

// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
  // Password is not matching 
} else {
  // Password is matching 
}
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
4

Here is the solution:

use Illuminate\Support\Facades\Hash;    
$password = request('password'); // get the value of password field
$hashed = Hash::make($password); // encrypt the password

N.B: Use 1st line code at the very beginning in your controller. Last but not the least, use the rest two lines of code inside the function of your controller where you want to manipulate with data after the from is submitted. Happy coding :)

Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
2

You can use the following:

$hashed_password = Hash::make('Your Unhashed Password');

You can find more information: here

Chris G
  • 6,700
  • 2
  • 18
  • 20
2
use Illuminate\Support\Facades\Hash;

You can use to hashing password => Hash::make('yourpassword');

You can use checking password => Hash::check($password, $user->password);

1

In the BcryptHasher.php you can find the hash code:

public function make($value, array $options = array())
{
    $cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;

    $hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));

            $hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));
            echo $value.' '.PASSWORD_BCRYPT.' '.$cost.' ';
            echo $hash;die();
    if ($hash === false)
    {
        throw new RuntimeException("Bcrypt hashing not supported.");
    }

    return $hash;
}
hendra1
  • 1,359
  • 1
  • 15
  • 24
1
use Illuminate\Support\Facades\Hash;
if(Hash::check($plain-text,$hashed-text))
    {
       return true;
    }
    else
    {
        return false;
    }

eg- $plain-text = 'text'; $hashed-text=Hash::make('text');

  • Yes. This is the right way. Need to use Illuminate\Support\Facades\Hash . Thank you! – Nole Nov 01 '19 at 10:15
1

Create a function

    
    public function bcryptGenerator($password)
    {
        return \bcrypt($password);
    }

Call the function

bcryptGenerator(123456);
// password = 123456
0

Compare password in laravel and lumen:

This may be possible that bcrypt function does not work with php7 then you can use below code in laravel and lumen as per your requirements:

use Illuminate\Support\Facades\Hash;

$test = app('hash')->make("test");
if (Hash::check('test', $test)) {
   echo "matched";
} else {
   echo "no matched";
}

I hope, this help will make you happy :)

Kamlesh
  • 5,233
  • 39
  • 50
0
 $data->password = Hash::make(($request->password));  //Password 
  Encripted  

//Login code

if ($data = AddEmployee::where('name', $request->name)->first()) {
        $pass = Hash::check($request->password, $data->password);
        if ($pass) {
            echo "sucess";
        } else {
            echo "Password Not Valid";
        }
    } else {
        echo "Username Not Valid" . "<br>";
    }
0

In the Controller which is used to insert the password, just use 'use Hash;'.

ouflak
  • 2,458
  • 10
  • 44
  • 49
-6

ok, this is a extract from the make function in hash.php

    $work = str_pad(8, 2, '0', STR_PAD_LEFT);

    // Bcrypt expects the salt to be 22 base64 encoded characters including
    // dots and slashes. We will get rid of the plus signs included in the
    // base64 data and replace them with dots.
    if (function_exists('openssl_random_pseudo_bytes'))
    {
        $salt = openssl_random_pseudo_bytes(16);
    }
    else
    {
        $salt = Str::random(40);
    }

    $salt = substr(strtr(base64_encode($salt), '+', '.'), 0 , 22);

    echo crypt('yourpassword', '$2a$'.$work.'$'.$salt);

Just copy/paste it into a php file and run it.

  • 1
    This is REALLY bad practice. Unless you're very proficient in cryptography, you should simply use the built in already made hashing functions. – Nick Jul 18 '17 at 21:37