forked from nette/security
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPasswords.php
More file actions
75 lines (61 loc) · 1.94 KB
/
Copy pathPasswords.php
File metadata and controls
75 lines (61 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
/**
* This file is part of the Nette Framework (http://nette.org)
* Copyright (c) 2004 David Grudl (http://davidgrudl.com)
*/
namespace Nette\Security;
use Nette;
/**
* Passwords tools. Requires PHP >= 5.3.7.
*
* @author David Grudl
*/
class Passwords
{
const BCRYPT_COST = 10;
/**
* Computes salted password hash.
* @param string
* @param array with cost (4-31), salt (22 chars)
* @return string 60 chars long
*/
public static function hash($password, array $options = NULL)
{
$cost = isset($options['cost']) ? (int) $options['cost'] : self::BCRYPT_COST;
$salt = isset($options['salt']) ? (string) $options['salt'] : Nette\Utils\Random::generate(22, '0-9A-Za-z./');
if (PHP_VERSION_ID < 50307) {
throw new Nette\NotSupportedException(__METHOD__ . ' requires PHP >= 5.3.7.');
} elseif (($len = strlen($salt)) < 22) {
throw new Nette\InvalidArgumentException("Salt must be 22 characters long, $len given.");
} elseif ($cost < 4 || $cost > 31) {
throw new Nette\InvalidArgumentException("Cost must be in range 4-31, $cost given.");
}
$hash = crypt($password, '$2y$' . ($cost < 10 ? 0 : '') . $cost . '$' . $salt);
if (strlen($hash) < 60) {
throw new Nette\InvalidStateException('Hash returned by crypt is invalid.');
}
return $hash;
}
/**
* Verifies that a password matches a hash.
* @return bool
*/
public static function verify($password, $hash)
{
return preg_match('#^\$2y\$(?P<cost>\d\d)\$(?P<salt>.{22})#', $hash, $m)
&& $m['cost'] >= 4 && $m['cost'] <= 31
&& self::hash($password, $m) === $hash;
}
/**
* Checks if the given hash matches the options.
* @param string
* @param array with cost (4-31)
* @return bool
*/
public static function needsRehash($hash, array $options = NULL)
{
$cost = isset($options['cost']) ? (int) $options['cost'] : self::BCRYPT_COST;
return !preg_match('#^\$2y\$(?P<cost>\d\d)\$(?P<salt>.{22})#', $hash, $m)
|| $m['cost'] < $cost;
}
}