| 1 |
<?php |
| 2 |
namespace Aws\Crypto; |
| 3 |
|
| 4 |
use Aws\Kms\KmsClient; |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
class KmsMaterialsProvider extends MaterialsProvider implements MaterialsProviderInterface |
| 17 |
{ |
| 18 |
const WRAP_ALGORITHM_NAME = 'kms'; |
| 19 |
|
| 20 |
private $kmsClient; |
| 21 |
private $kmsKeyId; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
public function __construct( |
| 30 |
KmsClient $kmsClient, |
| 31 |
$kmsKeyId = null |
| 32 |
) { |
| 33 |
$this->kmsClient = $kmsClient; |
| 34 |
$this->kmsKeyId = $kmsKeyId; |
| 35 |
} |
| 36 |
|
| 37 |
public function fromDecryptionEnvelope(MetadataEnvelope $envelope) |
| 38 |
{ |
| 39 |
if (empty($envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER])) { |
| 40 |
throw new \RuntimeException('Not able to detect the materials description.'); |
| 41 |
} |
| 42 |
|
| 43 |
$materialsDescription = json_decode( |
| 44 |
$envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER], |
| 45 |
true |
| 46 |
); |
| 47 |
|
| 48 |
if (empty($materialsDescription['kms_cmk_id']) |
| 49 |
&& empty($materialsDescription['aws:x-amz-cek-alg'])) { |
| 50 |
throw new \RuntimeException('Not able to detect kms_cmk_id (legacy' |
| 51 |
. ' implementation) or aws:x-amz-cek-alg (current implementation)' |
| 52 |
. ' from kms materials description.'); |
| 53 |
} |
| 54 |
|
| 55 |
return new self( |
| 56 |
$this->kmsClient, |
| 57 |
isset($materialsDescription['kms_cmk_id']) |
| 58 |
? $materialsDescription['kms_cmk_id'] |
| 59 |
: null |
| 60 |
); |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
public function getMaterialsDescription() |
| 70 |
{ |
| 71 |
return ['kms_cmk_id' => $this->kmsKeyId]; |
| 72 |
} |
| 73 |
|
| 74 |
public function getWrapAlgorithmName() |
| 75 |
{ |
| 76 |
return self::WRAP_ALGORITHM_NAME; |
| 77 |
} |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
public function encryptCek($unencryptedCek, $materialDescription) |
| 92 |
{ |
| 93 |
$encryptedDataKey = $this->kmsClient->encrypt([ |
| 94 |
'Plaintext' => $unencryptedCek, |
| 95 |
'KeyId' => $this->kmsKeyId, |
| 96 |
'EncryptionContext' => $materialDescription |
| 97 |
]); |
| 98 |
return base64_encode($encryptedDataKey['CiphertextBlob']); |
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
public function decryptCek($encryptedCek, $materialDescription) |
| 113 |
{ |
| 114 |
$result = $this->kmsClient->decrypt([ |
| 115 |
'CiphertextBlob' => $encryptedCek, |
| 116 |
'EncryptionContext' => $materialDescription |
| 117 |
]); |
| 118 |
|
| 119 |
return $result['Plaintext']; |
| 120 |
} |
| 121 |
} |