Hasher


Hashing

Zap Hasher class is a small, simple utility for generating hash from string (typically string without space), verify it (e.g., for password verification), and generating UUIDv4.

To create a hash, you can pass the string to has into the hash(string $string) method after instantiating the class.

use Zap\Core\Utils\Hasher;
$string = "somestring";
$hasher = new Hasher;
$hash = $hasher->hash($string);
// resulting $2y$10$5A16bHammnJVmYXfOL5r...

If you do this in the controller method, remember that you can pass the class as a dependency to the method, such as public function generateHash(Hasher $hasher){...}

The hash is generated by using password_hash() with PASSWORD_BCRYPT. You can modify options like cost right in the class file core/Utils/Flasher.php.

Verification

To verify whether a string and hash match, you can use the verify(string $hash, string $string) method. This method returns boolean: true if match, otherwise, false. This is useful for password verification.

You can verify password in the model or controller method after retrieving the user's hash password from the database. In the controller method, you can do this:

use Zap\Core\Utils\Hasher;
public function login(Request $request, Hasher $hasher) {
$loginData = [
 'username' => $request->input('username'),
 // and so on
];
$userData = $this->model('UsersModel')->getUserData($loginData);
// assuming that the account exists;
if(!$hasher->verify($userData['password'], $loginData['password'])){
 // throw error message
}
// rest of the code
}

Generating UUID V4

UUID stands for Universally Unique Identifier. It is a 128-bit number shown as a 36-character text string that identifies information or objects. A UUID is designed to guarantee nearly absolute uniqueness.

There are various versions of UUID, and Zap uses UUID version 4, which uses pure random numbers, and is the most popular choice. The primary advantage of UUID Version 4 lies in its randomness. Each generated UUID is statistically independent of any other UUID, making collisions highly unlikely.

You can use UUID to identify anything in the database, but this should not replace the autoincremental ID (e.g., for users' IDs).

use Zap\Core\Utils\Hasher;
$hasher = new Hasher;
$uuid = $hasher->generateUUIDv4();
// returning something like 3094af07-1fad-452f-86...

If the UUID is generated in the view, you can use use the service() helper.

<input type="hidden" name="uuid" value="{{ service('Zap\Core\Utils\Hasher')->generateUUIDv4() }}" readonly required />