November 30, 2016 —John Koster
Hashing data is a common task in software development. Hashing is similar to encryption, with the difference that hashing is a one-way process. The goal is that the original message cannot be retrieved from the resulting hash. Hashing is accomplished through the use of a hash function. A hash function generally accepts some input, called a message and transforms the message to produce a given output, a digest. Laravel, as it does with many other things, defines a Illuminate\Contracts\Hashing\Hasher
interface, which can be implemented to create new hashing providers that Laravel can use.
Any type that implements the Hasher
interface must be able to generate a hash (by implementing the make($value, array $options = [])
method), check that a value matches a hashed value (by implemented the check($value, $hashedValue, array $options = [])
method) and a hasher must be able to determine if a given hashed value needs to be rehashed (by implementing the needsRehash($hashedValue, array $options = [])
method).
A lot of newcomers to Laravel, and programming in general, seem to be confused about the differences between hashing and encryption. Hashing is one way; the point is that the final result is not recoverable. Encryption, conversely, is two-way; and the final result is reversible given enough information.
Another point of confusion is where Laravel stores the salts for password hashes in the database. In the case of newer PHP password hashing APIs, the salt, along with any other information required to compute the hash, is stored with the hash in the database.
Laravel internally utilizes a Hasher
implementation in a few scenarios, mostly having to deal with users and their passwords. At the time of writing, Laravel uses hashing in the following classes/services:
Class | Purpose |
---|---|
Illumiante\Auth\EloquentUserProvider | Validates a user against credentials that are passed into the validateCredentials method. |
Illumiante\Auth\DatabaseUserProvider | Validates a user against credentials that are passed into the validateCredentials method. |
Laravel provides one Hasher
implementation right out of the box: the Illuminate\Hashing\Bcrypt
hasher, which provides bcrypt password hashing, a hashing function based on the Blowfish cipher. The Bcrypt
hasher implements all methods defined in the Hasher
interface, and also provides one extra: setRounds($rounds)
, which is used to set work factor for the bcrypt hashing function.
∎
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.