in src/main/java/com/amazonaws/encryptionsdk/kms/AwsKmsMrkAwareMasterKey.java [332:384]
static DataKey<AwsKmsMrkAwareMasterKey> decryptSingleEncryptedDataKey(
final AwsKmsMrkAwareMasterKey masterKey,
final AWSKMS 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 DecryptResult decryptResult =
client.decrypt(
updateUserAgent(
new DecryptRequest()
.withCiphertextBlob(ByteBuffer.wrap(edk.getEncryptedDataKey()))
.withEncryptionContext(encryptionContext)
.withGrantTokens(grantTokens)
.withKeyId(awsKmsIdentifier)));
final String decryptResultKeyId = decryptResult.getKeyId();
if (decryptResultKeyId == 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(decryptResultKeyId)) {
throw new IllegalStateException(
"Received an invalid response from KMS Decrypt call: Unexpected keyId.");
}
// = 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 (decryptResult.getPlaintext().limit() != algorithm.getDataKeyLength()) {
throw new IllegalStateException("Received an unexpected number of bytes from KMS");
}
final byte[] rawKey = new byte[algorithm.getDataKeyLength()];
decryptResult.getPlaintext().get(rawKey);
return new DataKey<>(
new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()),
edk.getEncryptedDataKey(),
edk.getProviderInformation(),
masterKey);
}