[php] How to create a laravel hashed password

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

This question is related to php security laravel hash passwords

The answer is


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');


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


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 :)


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 :)


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


You can use the following:

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

You can find more information: here


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;
}

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 
}

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.


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');


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


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to security

Monitoring the Full Disclosure mailinglist Two Page Login with Spring Security 3.2.x How to prevent a browser from storing passwords JWT authentication for ASP.NET Web API How to use a client certificate to authenticate and authorize in a Web API Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How does Content Security Policy (CSP) work? How to prevent Screen Capture in Android Default SecurityProtocol in .NET 4.5

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to hash

php mysqli_connect: authentication method unknown to the client [caching_sha2_password] What is Hash and Range Primary Key? How to create a laravel hashed password Hashing a file in Python PHP salt and hash SHA256 for login password Append key/value pair to hash with << in Ruby Are there any SHA-256 javascript implementations that are generally considered trustworthy? How do I generate a SALT in Java for Salted-Hash? What does hash do in python? Hashing with SHA1 Algorithm in C#

Examples related to passwords

Your password does not satisfy the current policy requirements Laravel Password & Password_Confirmation Validation Default password of mysql in ubuntu server 16.04 mcrypt is deprecated, what is the alternative? What is the default root pasword for MySQL 5.7 MySQL user DB does not have password columns - Installing MySQL on OSX Changing an AIX password via script? Hide password with "•••••••" in a textField How to create a laravel hashed password Enter export password to generate a P12 certificate