SignatureTrait.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace Aws\Signature;
  3. /**
  4. * Provides signature calculation for SignatureV4.
  5. */
  6. trait SignatureTrait
  7. {
  8. /** @var array Cache of previously signed values */
  9. private $cache = [];
  10. /** @var int Size of the hash cache */
  11. private $cacheSize = 0;
  12. private function createScope($shortDate, $region, $service)
  13. {
  14. return "$shortDate/$region/$service/aws4_request";
  15. }
  16. private function getSigningKey($shortDate, $region, $service, $secretKey)
  17. {
  18. $k = $shortDate . '_' . $region . '_' . $service . '_' . $secretKey;
  19. if (!isset($this->cache[$k])) {
  20. // Clear the cache when it reaches 50 entries
  21. if (++$this->cacheSize > 50) {
  22. $this->cache = [];
  23. $this->cacheSize = 0;
  24. }
  25. $dateKey = hash_hmac(
  26. 'sha256',
  27. $shortDate,
  28. "AWS4{$secretKey}",
  29. true
  30. );
  31. $regionKey = hash_hmac('sha256', $region, $dateKey, true);
  32. $serviceKey = hash_hmac('sha256', $service, $regionKey, true);
  33. $this->cache[$k] = hash_hmac(
  34. 'sha256',
  35. 'aws4_request',
  36. $serviceKey,
  37. true
  38. );
  39. }
  40. return $this->cache[$k];
  41. }
  42. }