Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 16 |
|
0.00% |
0 / 5 |
CRAP | |
0.00% |
0 / 1 |
| helpers_PasswordHash | |
0.00% |
0 / 16 |
|
0.00% |
0 / 5 |
42 | |
0.00% |
0 / 1 |
| __construct | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| encrypt | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
6 | |||
| verify | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
2 | |||
| getAlgorithm | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| getSaltLength | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | use oat\generis\model\user\PasswordConstraintsException; |
| 4 | use oat\generis\model\user\PasswordConstraintsService; |
| 5 | |
| 6 | /** |
| 7 | * Password Hash class. |
| 8 | * |
| 9 | * An helper class focusing on password validation/generation. |
| 10 | */ |
| 11 | class helpers_PasswordHash |
| 12 | { |
| 13 | private $algorithm; |
| 14 | private $saltLength; |
| 15 | |
| 16 | public function __construct($algorithm, $saltLength) |
| 17 | { |
| 18 | $this->algorithm = $algorithm; |
| 19 | $this->saltLength = $saltLength; |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * @param $password |
| 24 | * |
| 25 | * @return string |
| 26 | * @throws PasswordConstraintsException |
| 27 | */ |
| 28 | public function encrypt($password) |
| 29 | { |
| 30 | |
| 31 | if (PasswordConstraintsService::singleton()->validate($password)) { |
| 32 | $salt = helpers_Random::generateString($this->getSaltLength()); |
| 33 | return $salt . hash($this->getAlgorithm(), $salt . $password); |
| 34 | } |
| 35 | |
| 36 | throw new PasswordConstraintsException( |
| 37 | __( |
| 38 | 'Password must be: %s', |
| 39 | implode(',', PasswordConstraintsService::singleton()->getErrors()) |
| 40 | ) |
| 41 | ); |
| 42 | } |
| 43 | |
| 44 | public function verify($password, $hash) |
| 45 | { |
| 46 | $salt = substr($hash, 0, $this->getSaltLength()); |
| 47 | $hashed = substr($hash, $this->getSaltLength()); |
| 48 | return hash($this->getAlgorithm(), $salt . $password) === $hashed; |
| 49 | } |
| 50 | |
| 51 | protected function getAlgorithm() |
| 52 | { |
| 53 | return $this->algorithm; |
| 54 | } |
| 55 | |
| 56 | protected function getSaltLength() |
| 57 | { |
| 58 | return $this->saltLength; |
| 59 | } |
| 60 | } |