Hashing

Lithe offers a security module called Hash with methods to create and verify hashes of sensitive data using the Bcrypt algorithm. Bcrypt is widely recognized for its security and efficiency in protecting passwords and other sensitive data.

Using Hash

Creating a Hash

You can create a hash from a string using the make method provided by Lithe's Hash security module. All hashes are generated using the Bcrypt algorithm.

use Lithe\Http\Request;
use Lithe\Http\Response;
use Lithe\Support\Security\Hash;
use function Lithe\Orbs\Http\Router\{get, post, route};

post('/user/register', function (Request $req, Response $res) {
    // Creating a hash for the 'password' field from the request body
    $hashedPassword = Hash::make($req->input('input'));

    // ...

    // Returning the response
    return $res->send("User registered successfully!");
});

Verifying a Hash

You can check if a string matches a hash using the check method provided by Lithe's Hash security module.

use Lithe\Support\Security\Hash;

$valid = Hash::check($plainPassword, $hashedPassword);

If the string matches the provided hash, the method returns true. Otherwise, it returns false.

Rehashing a Value

You can check if a hash needs rehashing and, if necessary, create a new hash with a different cost using the needsRehash method provided by Lithe's Hash security module.

use Lithe\Support\Security\Hash;

$needsRehash = Hash::needsRehash($hashedPassword, ['cost' => 12]);

If the hash needs rehashing, the method returns true. Otherwise, it returns false.

To handle rehashing appropriately, it is recommended to check if the hash needs rehashing and, if necessary, create a new hash and update the stored hash.

use Lithe\Support\Security\Hash;

if (Hash::needsRehash($hashedPassword, ['cost' => 12])) {
    $newHashedPassword = Hash::make($plainPassword, ['cost' => 12]);
    // Update the hash stored in the database
}