in src/main/java/com/amazonaws/encryptionsdk/kmssdkv2/AwsKmsMrkAwareMasterKey.java [342:397]
static DataKey<AwsKmsMrkAwareMasterKey> decryptSingleEncryptedDataKey(
final AwsKmsMrkAwareMasterKey masterKey,
final KmsClient client,
final String awsKmsIdentifier,
final List<String> grantTokens,
final CryptoAlgorithm algorithm,
final EncryptedDataKey edk,
final Map<String, String> encryptionContext) {
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// # To decrypt the encrypted data key this master key MUST use the
// # configured AWS KMS client to make an AWS KMS Decrypt
// # (https://docs.aws.amazon.com/kms/latest/APIReference/
// # API_Decrypt.html) request constructed as follows:
final DecryptResponse decryptResponse =
client.decrypt(
DecryptRequest.builder()
.overrideConfiguration(API_NAME_INTERCEPTOR)
.ciphertextBlob(SdkBytes.fromByteArray(edk.getEncryptedDataKey()))
.encryptionContext(encryptionContext)
.grantTokens(grantTokens)
.keyId(awsKmsIdentifier)
.build());
final String decryptResponseKeyId = decryptResponse.keyId();
/* Exceptional Postcondition: Must have a CMK ARN from AWS KMS to match. */
if (decryptResponseKeyId == null) {
throw new IllegalStateException("Received an empty keyId from KMS");
}
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// # If the call succeeds then the response's "KeyId" MUST be equal to the
// # configured AWS KMS key identifier otherwise the function MUST collect
// # an error.
if (!awsKmsIdentifier.equals(decryptResponseKeyId)) {
throw new IllegalStateException(
"Received an invalid response from KMS Decrypt call: Unexpected keyId.");
}
final ByteBuffer plaintextBuffer = decryptResponse.plaintext().asByteBuffer();
// = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9
// # The response's "Plaintext"'s length MUST equal the length
// # required by the requested algorithm suite otherwise the function MUST
// # collect an error.
if (plaintextBuffer.limit() != algorithm.getDataKeyLength()) {
throw new IllegalStateException("Received an unexpected number of bytes from KMS");
}
final byte[] rawKey = new byte[algorithm.getDataKeyLength()];
plaintextBuffer.get(rawKey);
return new DataKey<>(
new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()),
edk.getEncryptedDataKey(),
edk.getProviderInformation(),
masterKey);
}