AesGcmDecryptingStream.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace Aws\Crypto;
  3. use Aws\Exception\CryptoException;
  4. use GuzzleHttp\Psr7;
  5. use GuzzleHttp\Psr7\StreamDecoratorTrait;
  6. use Psr\Http\Message\StreamInterface;
  7. use Aws\Crypto\Polyfill\AesGcm;
  8. use Aws\Crypto\Polyfill\Key;
  9. /**
  10. * @internal Represents a stream of data to be gcm decrypted.
  11. */
  12. class AesGcmDecryptingStream implements AesStreamInterface
  13. {
  14. use StreamDecoratorTrait;
  15. private $aad;
  16. private $initializationVector;
  17. private $key;
  18. private $keySize;
  19. private $cipherText;
  20. private $tag;
  21. private $tagLength;
  22. /**
  23. * @param StreamInterface $cipherText
  24. * @param string $key
  25. * @param string $initializationVector
  26. * @param string $tag
  27. * @param string $aad
  28. * @param int $tagLength
  29. * @param int $keySize
  30. */
  31. public function __construct(
  32. StreamInterface $cipherText,
  33. $key,
  34. $initializationVector,
  35. $tag,
  36. $aad = '',
  37. $tagLength = 128,
  38. $keySize = 256
  39. ) {
  40. $this->cipherText = $cipherText;
  41. $this->key = $key;
  42. $this->initializationVector = $initializationVector;
  43. $this->tag = $tag;
  44. $this->aad = $aad;
  45. $this->tagLength = $tagLength;
  46. $this->keySize = $keySize;
  47. }
  48. public function getOpenSslName()
  49. {
  50. return "aes-{$this->keySize}-gcm";
  51. }
  52. public function getAesName()
  53. {
  54. return 'AES/GCM/NoPadding';
  55. }
  56. public function getCurrentIv()
  57. {
  58. return $this->initializationVector;
  59. }
  60. public function createStream()
  61. {
  62. if (version_compare(PHP_VERSION, '7.1', '<')) {
  63. return Psr7\stream_for(AesGcm::decrypt(
  64. (string) $this->cipherText,
  65. $this->initializationVector,
  66. new Key($this->key),
  67. $this->aad,
  68. $this->tag,
  69. $this->keySize
  70. ));
  71. } else {
  72. $result = \openssl_decrypt(
  73. (string)$this->cipherText,
  74. $this->getOpenSslName(),
  75. $this->key,
  76. OPENSSL_RAW_DATA,
  77. $this->initializationVector,
  78. $this->tag,
  79. $this->aad
  80. );
  81. if ($result === false) {
  82. throw new CryptoException('The requested object could not be'
  83. . ' decrypted due to an invalid authentication tag.');
  84. }
  85. return Psr7\stream_for($result);
  86. }
  87. }
  88. public function isWritable()
  89. {
  90. return false;
  91. }
  92. }