Hash


Basic usage

  • ##Introduction Laravel
  • Hash
  • facade provides secure Bcrypt and Argon2 hash encryption methods for storing user passwords. If you use the built-in LoginController and
  • RegisterController
classes in your Laravel application, they use Bcrypt for registration and authentication by default.

{tip} Bcrypt is ideal for hashing passwords because its "encryption coefficient" can be adjusted arbitrarily, which means that the time required to generate a hash can be increased with the hardware power. Increase.

ConfigurationYou can configure the file in config/hashing.php

Configure the default hash driver in . Three drivers are currently supported:
Bcrypt

and

Argon2
(Argon2i and Argon2id variants).

{note} The Argon2i driver requires PHP 7.2.0 or higher, and the Argon2id driver requires PHP 7.3.0 or higher.

##Basic usageYou can call Hash facade’s

make
Method to encrypt your password:

<?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Hash;
    use App\Http\Controllers\Controller;class UpdatePasswordController extends Controller{ 
    /**
     * 更新用户密码。
     *
     * @param  Request  $request
     * @return Response
     */    
  public function update(Request $request)   
   {       
    // 验证新密码的长度        
    $request->user()->fill([        
        'password' => Hash::make($request->newPassword)      
      ])->save();  
    }
 }

Adjust the Bcrypt encryption coefficient

If you use the Bcrypt algorithm, you can use the rounds option in the make method to configure the encryption coefficient of the algorithm. However, for most applications, the default value is sufficient:

$hashed = Hash::make('password', [ 
   'rounds' => 12
]);

Adjust the Argon2 encryption coefficient

If using the Argon2 algorithm, you can Use the memory, time and threads options in the make method to configure the encryption coefficient of the algorithm. Then, for most applications, the default values ​​will be sufficient:

$hashed = Hash::make('password', [ 
   'memory' => 1024,    
   'time' => 2,    
   'threads' => 2,
]);

{tip} For more information on these options, consult the PHP Official Documentation.

Password Hash Verification

check method can verify that a given unencrypted string matches the given hash Whether the expected values ​​are consistent. However, if you use Laravel's built-in LoginController controller, you may not need to use this method directly because the controller will automatically call this method:

if (Hash::check('plain-text', $hashedPassword)) { 
   // 密码匹配
 }

Check if the password needs to be rehashed

needsRehash method can check for you whether your password has been re-encrypted with the new encryption coefficient when the encryption coefficient of the hash is changed:

if (Hash::needsRehash($hashed)) { 
   $hashed = Hash::make('plain-text');
 }
This article was first published on the LearnKu.com website.