|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Trait implementation of repetitive/recursive hashing for digestion algorithms. |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace CryptoManana\Core\Traits\MessageDigestion; |
|
8
|
|
|
|
|
9
|
|
|
use \CryptoManana\Core\Interfaces\MessageDigestion\RepetitiveHashingInterface as RepetitiveHashingSpecification; |
|
10
|
|
|
use \CryptoManana\Core\Abstractions\MessageDigestion\AbstractHashAlgorithm as AnyDerivedHashAlgorithm; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Trait RepetitiveHashingTrait - Reusable implementation of `RepetitiveHashingInterface`. |
|
14
|
|
|
* |
|
15
|
|
|
* @see \CryptoManana\Core\Interfaces\MessageDigestion\RepetitiveHashingInterface The abstract specification. |
|
16
|
|
|
* |
|
17
|
|
|
* @package CryptoManana\Core\Traits\MessageDigestion |
|
18
|
|
|
* |
|
19
|
|
|
* @mixin RepetitiveHashingSpecification |
|
20
|
|
|
* @mixin AnyDerivedHashAlgorithm |
|
21
|
|
|
*/ |
|
22
|
|
|
trait RepetitiveHashingTrait |
|
23
|
|
|
{ |
|
24
|
|
|
/** |
|
25
|
|
|
* Calculates a hash value for the given data. |
|
26
|
|
|
* |
|
27
|
|
|
* @param string $data The input string. |
|
28
|
|
|
* |
|
29
|
|
|
* @return string The digest. |
|
30
|
|
|
* @throws \Exception Validation errors. |
|
31
|
|
|
*/ |
|
32
|
|
|
abstract public function hashData($data); |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Calculates a hash value for the given data via repetitive/recursive digestion. |
|
36
|
|
|
* |
|
37
|
|
|
* @param string $data The input string. |
|
38
|
|
|
* @param int $iterations The number of internal iterations to perform. |
|
39
|
|
|
* |
|
40
|
|
|
* @return string The digest. |
|
41
|
|
|
* @throws \Exception Validation errors. |
|
42
|
|
|
*/ |
|
43
|
198 |
|
public function repetitiveHashData($data, $iterations = 2) |
|
44
|
|
|
{ |
|
45
|
198 |
|
$iterations = filter_var( |
|
46
|
198 |
|
$iterations, |
|
47
|
198 |
|
FILTER_VALIDATE_INT, |
|
48
|
|
|
[ |
|
49
|
|
|
"options" => [ |
|
50
|
198 |
|
"min_range" => 2, |
|
51
|
198 |
|
"max_range" => PHP_INT_MAX, |
|
52
|
|
|
], |
|
53
|
|
|
] |
|
54
|
|
|
); |
|
55
|
|
|
|
|
56
|
198 |
|
if ($iterations === false) { |
|
57
|
66 |
|
throw new \InvalidArgumentException('The repeated hashing times must be a valid integer bigger than 1.'); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
132 |
|
$oldDigestFormat = $this->digestFormat; |
|
61
|
132 |
|
$this->digestFormat = self::DIGEST_OUTPUT_RAW; |
|
|
|
|
|
|
62
|
|
|
|
|
63
|
132 |
|
for ($i = 1; $i < $iterations; $i++) { |
|
64
|
132 |
|
$data = $this->hashData($data); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
66 |
|
$this->digestFormat = $oldDigestFormat; |
|
68
|
|
|
|
|
69
|
66 |
|
return $this->hashData($data); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|