123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- <?php
- namespace Aws\Glacier;
- use Aws\HashInterface;
- class TreeHash implements HashInterface
- {
- const MB = 1048576;
- const EMPTY_HASH = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
-
- private $algorithm;
-
- private $buffer;
-
- private $checksums = [];
-
- private $hash;
- public function __construct($algorithm = 'sha256')
- {
- $this->algorithm = $algorithm;
- $this->reset();
- }
-
- public function update($data)
- {
-
- if ($this->hash) {
- throw new \LogicException('You may not add more data to a '
- . 'complete tree hash.');
- }
-
- $this->buffer .= $data;
-
- while (strlen($this->buffer) >= self::MB) {
- $data = substr($this->buffer, 0, self::MB);
- $this->buffer = substr($this->buffer, self::MB) ?: '';
- $this->checksums[] = hash($this->algorithm, $data, true);
- }
- return $this;
- }
-
- public function addChecksum($checksum, $inBinaryForm = false)
- {
-
- if ($this->hash) {
- throw new \LogicException('You may not add more checksums to a '
- . 'complete tree hash.');
- }
-
- $this->checksums[] = $inBinaryForm ? $checksum : hex2bin($checksum);
- return $this;
- }
- public function complete()
- {
- if (!$this->hash) {
-
- if (strlen($this->buffer) > 0) {
- $this->checksums[] = hash($this->algorithm, $this->buffer, true);
- $this->buffer = '';
- }
-
- if (!$this->checksums) {
- $this->checksums[] = hex2bin(self::EMPTY_HASH);
- }
-
- $hashes = $this->checksums;
- while (count($hashes) > 1) {
- $sets = array_chunk($hashes, 2);
- $hashes = array();
- foreach ($sets as $set) {
- $hashes[] = (count($set) === 1)
- ? $set[0]
- : hash($this->algorithm, $set[0] . $set[1], true);
- }
- }
- $this->hash = $hashes[0];
- }
- return $this->hash;
- }
- public function reset()
- {
- $this->hash = null;
- $this->checksums = [];
- $this->buffer = '';
- }
- }
|