| 1 |
<?php |
| 2 |
|
| 3 |
namespace Dudlewebs\WPMCS\s3\Aws\Crypto; |
| 4 |
|
| 5 |
use Dudlewebs\WPMCS\s3\Aws\Crypto\Polyfill\AesGcm; |
| 6 |
use Dudlewebs\WPMCS\s3\Aws\Crypto\Polyfill\Key; |
| 7 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\Psr7; |
| 8 |
use Dudlewebs\WPMCS\s3\GuzzleHttp\Psr7\StreamDecoratorTrait; |
| 9 |
use Dudlewebs\WPMCS\s3\Psr\Http\Message\StreamInterface; |
| 10 |
use RuntimeException; |
| 11 |
/** |
| 12 |
* @internal Represents a stream of data to be gcm encrypted. |
| 13 |
*/ |
| 14 |
class AesGcmEncryptingStream implements AesStreamInterface, AesStreamInterfaceV2 |
| 15 |
{ |
| 16 |
use StreamDecoratorTrait; |
| 17 |
private $aad; |
| 18 |
private $initializationVector; |
| 19 |
private $key; |
| 20 |
private $keySize; |
| 21 |
private $plaintext; |
| 22 |
private $tag = ''; |
| 23 |
private $tagLength; |
| 24 |
/** |
| 25 |
* Same as non-static 'getAesName' method, allowing calls in a static |
| 26 |
* context. |
| 27 |
* |
| 28 |
* @return string |
| 29 |
*/ |
| 30 |
public static function getStaticAesName() |
| 31 |
{ |
| 32 |
return 'AES/GCM/NoPadding'; |
| 33 |
} |
| 34 |
/** |
| 35 |
* @param StreamInterface $plaintext |
| 36 |
* @param string $key |
| 37 |
* @param string $initializationVector |
| 38 |
* @param string $aad |
| 39 |
* @param int $tagLength |
| 40 |
* @param int $keySize |
| 41 |
*/ |
| 42 |
public function __construct(StreamInterface $plaintext, $key, $initializationVector, $aad = '', $tagLength = 16, $keySize = 256) |
| 43 |
{ |
| 44 |
$this->plaintext = $plaintext; |
| 45 |
$this->key = $key; |
| 46 |
$this->initializationVector = $initializationVector; |
| 47 |
$this->aad = $aad; |
| 48 |
$this->tagLength = $tagLength; |
| 49 |
$this->keySize = $keySize; |
| 50 |
} |
| 51 |
public function getOpenSslName() |
| 52 |
{ |
| 53 |
return "aes-{$this->keySize}-gcm"; |
| 54 |
} |
| 55 |
/** |
| 56 |
* Same as static method and retained for backwards compatibility |
| 57 |
* |
| 58 |
* @return string |
| 59 |
*/ |
| 60 |
public function getAesName() |
| 61 |
{ |
| 62 |
return self::getStaticAesName(); |
| 63 |
} |
| 64 |
public function getCurrentIv() |
| 65 |
{ |
| 66 |
return $this->initializationVector; |
| 67 |
} |
| 68 |
public function createStream() |
| 69 |
{ |
| 70 |
if (\version_compare(\PHP_VERSION, '7.1', '<')) { |
| 71 |
return Psr7\Utils::streamFor(AesGcm::encrypt((string) $this->plaintext, $this->initializationVector, new Key($this->key), $this->aad, $this->tag, $this->keySize)); |
| 72 |
} else { |
| 73 |
return Psr7\Utils::streamFor(\openssl_encrypt((string) $this->plaintext, $this->getOpenSslName(), $this->key, \OPENSSL_RAW_DATA, $this->initializationVector, $this->tag, $this->aad, $this->tagLength)); |
| 74 |
} |
| 75 |
} |
| 76 |
/** |
| 77 |
* @return string |
| 78 |
*/ |
| 79 |
public function getTag() |
| 80 |
{ |
| 81 |
return $this->tag; |
| 82 |
} |
| 83 |
public function isWritable() |
| 84 |
{ |
| 85 |
return \false; |
| 86 |
} |
| 87 |
} |
| 88 |
|