Password Hashing

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. Class Nette\Security\Passwords will help us with this.

Following examples expect this alias:

use Nette\Security\Passwords;

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

Will generate 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.

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

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

This method generates password´s hash using a modern algorithm.

$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)) {
	// This will run, if password matches the fingerprint (hash)
} else {
	// This will run, if password does not match the fingerprint (hash)
}

needsRehash(string $password, array $options=null): bool

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
}