|
11 | 11 | namespace Robin\Ntlm\Crypt\Hasher; |
12 | 12 |
|
13 | 13 | use HashContext; |
| 14 | +use InvalidArgumentException; |
14 | 15 |
|
15 | 16 | /** |
16 | 17 | * A cryptographic hasher implemented using PHP's built-in hashing mechanisms as |
|
20 | 21 | */ |
21 | 22 | abstract class AbstractHasher implements HasherInterface |
22 | 23 | { |
| 24 | + |
| 25 | + /** |
| 26 | + * Constants |
| 27 | + */ |
| 28 | + |
| 29 | + /** |
| 30 | + * The "resource" type of a PHP hash context. |
| 31 | + * |
| 32 | + * @type string |
| 33 | + */ |
| 34 | + |
| 35 | + const HASH_CONTEXT_RESOURCE_TYPE = 'Hash Context'; |
| 36 | + |
| 37 | + |
| 38 | + /** |
| 39 | + * Properties |
| 40 | + */ |
| 41 | + |
23 | 42 | /** |
24 | 43 | * The incremental hashing context. |
25 | 44 | * |
26 | | - * @type HashContext |
| 45 | + * @link http://php.net/manual/en/hash.resources.php |
| 46 | + * @type resource|HashContext |
27 | 47 | */ |
28 | 48 | private $context; |
29 | 49 |
|
| 50 | + |
| 51 | + /** |
| 52 | + * Methods |
| 53 | + */ |
| 54 | + |
30 | 55 | /** |
31 | 56 | * Constructor |
32 | 57 | * |
33 | | - * @param HashContext $context The incremental hashing context. |
| 58 | + * @param resource|HashContext $context The incremental hashing context. |
34 | 59 | */ |
35 | | - protected function __construct(HashContext $context) |
| 60 | + protected function __construct($context) |
36 | 61 | { |
37 | | - $this->context = $context; |
| 62 | + $this->context = $this->validateHashContext($context); |
38 | 63 | } |
39 | 64 |
|
40 | 65 | /** |
@@ -63,4 +88,25 @@ public function digest(): string |
63 | 88 |
|
64 | 89 | return $digest; |
65 | 90 | } |
| 91 | + |
| 92 | + /** |
| 93 | + * Validates a given incremental hashing context. |
| 94 | + * |
| 95 | + * @link http://php.net/manual/en/hash.resources.php |
| 96 | + * @param mixed $context The context to validate. |
| 97 | + * @return resource|HashContext The incremental hashing context. |
| 98 | + * @throws InvalidArgumentException If the hash context isn't valid. |
| 99 | + */ |
| 100 | + protected function validateHashContext($context) |
| 101 | + { |
| 102 | + if (!($context instanceof HashContext) && (false === $context |
| 103 | + || !is_resource($context) |
| 104 | + || (is_resource($context) && static::HASH_CONTEXT_RESOURCE_TYPE !== get_resource_type($context)))) { |
| 105 | + throw new InvalidArgumentException( |
| 106 | + 'Unable to initialize hashing context. Your system might not support the supplied algorithm.' |
| 107 | + ); |
| 108 | + } |
| 109 | + |
| 110 | + return $context; |
| 111 | + } |
66 | 112 | } |
0 commit comments