CalculatesChecksumTrait.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace Aws\S3;
  3. use AWS\CRT\CRT;
  4. use Aws\Exception\CommonRuntimeException;
  5. use GuzzleHttp\Psr7;
  6. use InvalidArgumentException;
  7. trait CalculatesChecksumTrait
  8. {
  9. /**
  10. * @param string $requestedAlgorithm the algorithm to encode with
  11. * @param string $value the value to be encoded
  12. * @return string
  13. */
  14. public static function getEncodedValue($requestedAlgorithm, $value) {
  15. $requestedAlgorithm = strtolower($requestedAlgorithm);
  16. $useCrt = extension_loaded('awscrt');
  17. if ($useCrt) {
  18. $crt = new Crt();
  19. switch ($requestedAlgorithm) {
  20. case 'crc32c':
  21. return base64_encode(pack('N*',($crt->crc32c($value))));
  22. case 'crc32':
  23. return base64_encode(pack('N*',($crt->crc32($value))));
  24. case 'sha256':
  25. case 'sha1':
  26. return base64_encode(Psr7\Utils::hash($value, $requestedAlgorithm, true));
  27. default:
  28. break;
  29. throw new InvalidArgumentException(
  30. "Invalid checksum requested: {$requestedAlgorithm}."
  31. . " Valid algorithms are CRC32C, CRC32, SHA256, and SHA1."
  32. );
  33. }
  34. } else {
  35. if ($requestedAlgorithm == 'crc32c') {
  36. throw new CommonRuntimeException("crc32c is not supported for checksums "
  37. . "without use of the common runtime for php. Please enable the CRT or choose "
  38. . "a different algorithm."
  39. );
  40. }
  41. if ($requestedAlgorithm == "crc32") {
  42. $requestedAlgorithm = "crc32b";
  43. }
  44. return base64_encode(Psr7\Utils::hash($value, $requestedAlgorithm, true));
  45. }
  46. }
  47. }