| 1 |
<?php |
| 2 |
namespace Aws\S3; |
| 3 |
|
| 4 |
use AWS\CRT\CRT; |
| 5 |
use Aws\Exception\CommonRuntimeException; |
| 6 |
use GuzzleHttp\Psr7; |
| 7 |
use InvalidArgumentException; |
| 8 |
|
| 9 |
trait CalculatesChecksumTrait |
| 10 |
{ |
| 11 |
public static array $supportedAlgorithms = [ |
| 12 |
'crc32c' => true, |
| 13 |
'crc32' => true, |
| 14 |
'sha256' => true, |
| 15 |
'sha1' => true |
| 16 |
]; |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
public static function getEncodedValue($requestedAlgorithm, $value) { |
| 24 |
$requestedAlgorithm = strtolower($requestedAlgorithm); |
| 25 |
$useCrt = extension_loaded('awscrt'); |
| 26 |
|
| 27 |
if (isset(self::$supportedAlgorithms[$requestedAlgorithm])) { |
| 28 |
if ($useCrt) { |
| 29 |
$crt = new Crt(); |
| 30 |
switch ($requestedAlgorithm) { |
| 31 |
case 'crc32c': |
| 32 |
return base64_encode(pack('N*',($crt::crc32c($value)))); |
| 33 |
case 'crc32': |
| 34 |
return base64_encode(pack('N*',($crt::crc32($value)))); |
| 35 |
default: |
| 36 |
break; |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
if ($requestedAlgorithm === 'crc32c') { |
| 41 |
throw new CommonRuntimeException("crc32c is not supported for checksums " |
| 42 |
. "without use of the common runtime for php. Please enable the CRT or choose " |
| 43 |
. "a different algorithm." |
| 44 |
); |
| 45 |
} |
| 46 |
|
| 47 |
if ($requestedAlgorithm === "crc32") { |
| 48 |
$requestedAlgorithm = "crc32b"; |
| 49 |
} |
| 50 |
|
| 51 |
return base64_encode( |
| 52 |
Psr7\Utils::hash(Psr7\Utils::streamFor($value), |
| 53 |
$requestedAlgorithm, |
| 54 |
true |
| 55 |
) |
| 56 |
); |
| 57 |
} |
| 58 |
|
| 59 |
$validAlgorithms = implode(', ', array_keys(self::$supportedAlgorithms)); |
| 60 |
throw new InvalidArgumentException( |
| 61 |
"Invalid checksum requested: {$requestedAlgorithm}." |
| 62 |
. " Valid algorithms supported by the runtime are {$validAlgorithms}." |
| 63 |
); |
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
public static function filterChecksum(array $parameters): ?string |
| 74 |
{ |
| 75 |
foreach (self::$supportedAlgorithms as $algorithm => $_) { |
| 76 |
$checksumAlgorithm = "Checksum" . strtoupper($algorithm); |
| 77 |
if (isset($parameters[$checksumAlgorithm])) { |
| 78 |
return $checksumAlgorithm; |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
return null; |
| 83 |
} |
| 84 |
} |