|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace SilverStripe\Security; |
| 4 | + |
| 5 | +use RuntimeException; |
| 6 | + |
| 7 | +/** |
| 8 | + * Provides Password-Based Key Derivation Function hashing for passwords, using the provided algorithm (default |
| 9 | + * is SHA512), which is NZISM compliant under version 3.2 section 17.2. |
| 10 | + */ |
| 11 | +class PasswordEncryptorPBKDF2 extends PasswordEncryptor |
| 12 | +{ |
| 13 | + private string $algorithm = 'sha512'; |
| 14 | + |
| 15 | + /** |
| 16 | + * The number of internal iterations for hash_pbkdf2() to perform for the derivation. Please note that if you |
| 17 | + * change this from the default value you will break existing hashes stored in the database, so these would |
| 18 | + * need to be regenerated. |
| 19 | + */ |
| 20 | + private int $iterations = 30000; |
| 21 | + |
| 22 | + /** |
| 23 | + * @throws RuntimeException If the provided algorithm is not available in the current environment |
| 24 | + */ |
| 25 | + public function __construct(string $algorithm, ?int $iterations = null) |
| 26 | + { |
| 27 | + if (!in_array($algorithm, hash_hmac_algos())) { |
| 28 | + throw new RuntimeException( |
| 29 | + sprintf('Hash algorithm "%s" not found in hash_hmac_algos()', $algorithm) |
| 30 | + ); |
| 31 | + } |
| 32 | + |
| 33 | + $this->algorithm = $algorithm; |
| 34 | + |
| 35 | + if ($iterations !== null) { |
| 36 | + $this->iterations = $iterations; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Get the name of the algorithm that will be used to hash the password |
| 42 | + */ |
| 43 | + public function getAlgorithm(): string |
| 44 | + { |
| 45 | + return $this->algorithm; |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Get the number of iterations that will be used to hash the password |
| 50 | + */ |
| 51 | + public function getIterations(): int |
| 52 | + { |
| 53 | + return $this->iterations; |
| 54 | + } |
| 55 | + |
| 56 | + public function encrypt($password, $salt = null, $member = null) |
| 57 | + { |
| 58 | + return hash_pbkdf2( |
| 59 | + $this->getAlgorithm() ?? '', |
| 60 | + (string) $password, |
| 61 | + (string) $salt, |
| 62 | + $this->getIterations() ?? 0 |
| 63 | + ); |
| 64 | + } |
| 65 | +} |
0 commit comments