| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\Aws; |
| 4 |
|
| 5 |
/** |
| 6 |
* Incremental hashing using PHP's hash functions. |
| 7 |
*/ |
| 8 |
class PhpHash implements HashInterface |
| 9 |
{ |
| 10 |
/** @var resource|\HashContext */ |
| 11 |
private $context; |
| 12 |
/** @var string */ |
| 13 |
private $algo; |
| 14 |
/** @var array */ |
| 15 |
private $options; |
| 16 |
/** @var string */ |
| 17 |
private $hash; |
| 18 |
/** |
| 19 |
* @param string $algo Hashing algorithm. One of PHP's hash_algos() |
| 20 |
* return values (e.g. md5, sha1, etc...). |
| 21 |
* @param array $options Associative array of hashing options: |
| 22 |
* - key: Secret key used with the hashing algorithm. |
| 23 |
* - base64: Set to true to base64 encode the value when complete. |
| 24 |
*/ |
| 25 |
public function __construct($algo, array $options = []) |
| 26 |
{ |
| 27 |
$this->algo = $algo; |
| 28 |
$this->options = $options; |
| 29 |
} |
| 30 |
public function update($data) |
| 31 |
{ |
| 32 |
if ($this->hash !== null) { |
| 33 |
$this->reset(); |
| 34 |
} |
| 35 |
\hash_update($this->getContext(), $data); |
| 36 |
} |
| 37 |
public function complete() |
| 38 |
{ |
| 39 |
if ($this->hash) { |
| 40 |
return $this->hash; |
| 41 |
} |
| 42 |
$this->hash = \hash_final($this->getContext(), \true); |
| 43 |
if (isset($this->options['base64']) && $this->options['base64']) { |
| 44 |
$this->hash = \base64_encode($this->hash); |
| 45 |
} |
| 46 |
return $this->hash; |
| 47 |
} |
| 48 |
public function reset() |
| 49 |
{ |
| 50 |
$this->context = $this->hash = null; |
| 51 |
} |
| 52 |
/** |
| 53 |
* Get a hash context or create one if needed |
| 54 |
* |
| 55 |
* @return resource|\HashContext |
| 56 |
*/ |
| 57 |
private function getContext() |
| 58 |
{ |
| 59 |
if (!$this->context) { |
| 60 |
$key = isset($this->options['key']) ? $this->options['key'] : ''; |
| 61 |
$this->context = \hash_init($this->algo, $key ? \HASH_HMAC : 0, $key); |
| 62 |
} |
| 63 |
return $this->context; |
| 64 |
} |
| 65 |
} |
| 66 |
|