Password Hashing

To manage the security of our users, we never save their passwords in plaintext format, but we rather save the password´s fingerprint (eg. hash). There is no way to find out the real password from the password´s fingerprint. To create the fingerprint we have to use a save algorithm. Class Nette\Security\Passwords will help us with this.


composer require nette/utils

Following examples expect this alias:

use Nette\Security\Passwords;

__construct(int $algo = PASSWORD_DEFAULT, array $options=null)string

Will generate the password´s hash using a modern algorithm. We can set the cost parameter of range 4–31, which sets the number of iterations the algorithm takes to run. If we omit this parameter, a default value of 10 will be used.

The cost parameter is an exponent of function 2n. If we set its value too high, the hash computation will take too long. By using the highest value of 31 the computation takes approximately 64 hours.

// we will hash passwords with 12 iterations of the bcrypt algorithm
$passwords = new Passwords(PASSWORD_BCRYPT, ['cost' => 12]);

hash(string $passwords, array $options=null)string

This method generates password´s hash.

$hash = $passwords->hash($password); // Hashes the password

verify(string $password, string $hash)bool

This method finds out, if given password matches given fingerprint (hash).

if ($passwords->verify($password, $hash)) {

needsRehash(string $hash): bool

This method finds out if the hash matches given options in constructor.

if ($passwords->needsRehash($hash)) {