November 30, 2016 —John Koster
In this article we will create an implementation of Illuminate\Contracts\Hashing\Hasher
using PHP's crypt
function and the CRYPT_SHA512
hashing function. Like in the previous sections, we will examine each method before looking at the full implementation.
make($value, array $options = [])
The make
method is responsible for doing the actual hashing. It accepts an $options
array. We will allow a sixteen character long salt to be supplied using the options array. If no salt is supplied, we will generate one. We will also accept a rounds option, to control the number of iterations the hashing function will perform.
For the actual hashing, we will make a call to PHP's crypt
function.
public function check($value, $hashedValue, array $options = [])
The check
method is used to check that a known $value
is the same as a given $hashedValue
. We will not need any options for this method.
For the actual hashing, we will use PHP's crypt
function.
public function needsRehash($hashedValue, array $options = [])
The needsRehash
method is used to determine if a given hash needs to be updated, or rehashed. We will accept a salt as an option. If the salt from the $options
array does not match the salt from the $hashedValue
the $hashedValue
, or if the rounds from the $options
array does not match the rounds from the $hashedValue
, the $hashedValue
needs to be rehashed.
Sha512Hasher Option | Description |
---|---|
salt |
Users can supply their own four character salt to the make and needsRehash methods. If no salt is supplied for the make method, one will be generated. |
rounds |
Users can give an integer for the make and needsRehash methods to change the number of iterations the hashing function will perform. |
The following is the complete implementation of the Sha512Hasher
class. Because implementing CRYPT_SHA512
is almost identical to implementing CRYPT_SHA256
, and because the Sha256Hasher
class gets the value for the hashing function from the protected $shaPrefix
variable, we can simple extend the Sha256Hasher
class and make a simple change:
1<?php 2 3namespace Laravel\Artisan\Hashing; 4 5use Illuminate\Contracts\Hashing\Hasher as HasherContract; 6 7class Sha512Hasher extends Sha256Hasher implements HasherContract 8{ 9 10 /**11 * The prefix expected by the crpyt function.12 *13 * Changed to match the SHA-512 hashing function14 * prefix that can be found in the PHP docs at15 * http://php.net/manual/en/function.crypt.php16 *17 * @var string18 */19 protected $shaPrefix = '6';20 21}
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.