|
| 1 | +Working With Passwords - Nette\Security\Passwords |
| 2 | +************************************************* |
| 3 | + |
| 4 | +.[perex] |
| 5 | +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 |api:] will help us with this. |
| 6 | + |
| 7 | +Following examples expect this alias: |
| 8 | + |
| 9 | +/--php |
| 10 | +use Nette\Security\Passwords; |
| 11 | +\-- |
| 12 | + |
| 13 | + |
| 14 | +hash($passwords, array $options = NULL) |
| 15 | +======================================= |
| 16 | + |
| 17 | +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. |
| 18 | + |
| 19 | +.[warning] |
| 20 | +The `cost` parameter is an exponent of function 2^n. 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. |
| 21 | + |
| 22 | +/--php |
| 23 | +$hash = Passwords::hash($password); // Hashes the password |
| 24 | +$hash = Passwords::hash($password, ['cost' => 12]); // Hashes the password using 12 iterations of bcrypt algorithm |
| 25 | +\-- |
| 26 | + |
| 27 | +verify($password, $hash) |
| 28 | +======================== |
| 29 | + |
| 30 | +This method finds out, if given password matches given fingerprint (hash). |
| 31 | + |
| 32 | +/--php |
| 33 | +if (Passwords::verify($password, $hash)) { |
| 34 | + // This will run, if password matches the fingerprint (hash) |
| 35 | +} else { |
| 36 | + // This will run, if password does not match the fingerprint (hash) |
| 37 | +} |
| 38 | +\-- |
| 39 | + |
| 40 | +needsRehash($password, array $options = NULL) |
| 41 | +============================================= |
| 42 | + |
| 43 | +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. |
| 44 | + |
| 45 | +/--php |
| 46 | +if (Passwords::needsRehash($hash)) { |
| 47 | + // This will run, if the password needs to be rehashed |
| 48 | +} |
| 49 | +\-- |
0 commit comments