public DataKey encryptDataKey()

in src/main/java/com/amazonaws/encryptionsdk/kms/AwsKmsMrkAwareMasterKey.java [208:256]


  public DataKey<AwsKmsMrkAwareMasterKey> encryptDataKey(
      final CryptoAlgorithm algorithm,
      final Map<String, String> encryptionContext,
      final DataKey<?> dataKey) {
    final SecretKey key = dataKey.getKey();
    if (!key.getFormat().equals("RAW")) {
      throw new IllegalArgumentException("Only RAW encoded keys are supported");
    }

    try {
      // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
      // # The master
      // # key MUST use the configured AWS KMS client to make an AWS KMS Encrypt
      // # (https://docs.aws.amazon.com/kms/latest/APIReference/
      // # API_Encrypt.html) request constructed as follows:
      final EncryptResult encryptResult =
          kmsClient_.encrypt(
              updateUserAgent(
                  new EncryptRequest()
                      .withKeyId(awsKmsIdentifier_)
                      .withPlaintext(ByteBuffer.wrap(key.getEncoded()))
                      .withEncryptionContext(encryptionContext)
                      .withGrantTokens(grantTokens_)));

      final byte[] edk = new byte[encryptResult.getCiphertextBlob().remaining()];
      encryptResult.getCiphertextBlob().get(edk);
      final String encryptResultKeyId = encryptResult.getKeyId();
      // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
      // # The AWS KMS Encrypt response MUST contain a valid "KeyId".
      if (parseInfoFromKeyArn(encryptResultKeyId) == null) {
        throw new IllegalStateException("Received an empty or invalid keyId from KMS");
      }

      // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
      // # The output MUST be the same as the Master Key Encrypt Data Key
      // # (../master-key-interface.md#encrypt-data-key) interface.
      return new DataKey<>(
          dataKey.getKey(),
          // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11
          // # The
          // # response's cipher text blob MUST be used as the "ciphertext" for the
          // # encrypted data key.
          edk,
          encryptResultKeyId.getBytes(StandardCharsets.UTF_8),
          this);
    } catch (final AmazonServiceException asex) {
      throw new AwsCryptoException(asex);
    }
  }