Edit
Version 2.4

Working With Passwords – Nette\Security\Passwords

To manage 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. Static class Nette\Security\Passwords will help us with this.

Following examples expect this alias:

use Nette\Security\Passwords;

hash($passwords, array $options = NULL)

This method generates password´s hash using a modern bcrypt 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 compuauion takes approximately 64 hours.

$hash = Passwords::hash($password); // Hashes the password
$hash = Passwords::hash($password, ['cost' => 12]); // Hashes the password using 12 iterations of bcrypt algorithm

verify($password, $hash)

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

if (Passwords::verify($password, $hash)) {
    // This will run, if password matches the fingerprint (hash)
} else {
    // This will run, if password does not match the fingerprint (hash)
}

needsRehash($password, array $options = NULL)

This method finds out, if the hash matches given options. 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.

if (Passwords::needsRehash($hash)) {
    // This will run, if the password needs to be rehashed
}