

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

# AWS Encryption SDK for Java
<a name="java"></a>

Este tópico explica como instalar e usar o AWS Encryption SDK for Java. Para obter detalhes sobre a programação com o AWS Encryption SDK for Java, consulte o [aws-encryption-sdk-java](https://github.com/aws/aws-encryption-sdk-java/)repositório em GitHub. Para obter a documentação da API, consulte o [Javadoc](https://aws.github.io/aws-encryption-sdk-java/) para AWS Encryption SDK for Java.

**Topics**
+ [

## Pré-requisitos
](#java-prerequisites)
+ [

## Instalação
](#java-installation)
+ [Exemplos](java-example-code.md)

## Pré-requisitos
<a name="java-prerequisites"></a>

Antes de instalar o AWS Encryption SDK for Java, verifique se você tem os seguintes pré-requisitos.

**Um ambiente de desenvolvimento Java**  
Você precisará do Java 8 ou posterior. No site da Oracle, acesse [Java SE Downloads](https://www.oracle.com/java/technologies/downloads/) e faça download e instale o Java SE Development Kit (JDK).  
Se você usa o Oracle JDK, também precisara fazer download e instalar os [arquivos de política de jurisdição de força ilimitada JCE (Java Cryptography Extension)](http://www.oracle.com/java/technologies/javase-jce8-downloads.html).

**Bouncy Castle**  
 AWS Encryption SDK for Java Isso requer o [Bouncy Castle.](https://www.bouncycastle.org/download/bouncy-castle-java/)   
+ AWS Encryption SDK for Java as versões 1.6.1 e posteriores usam o Bouncy Castle para serializar e desserializar objetos criptográficos. Você pode usar o Bouncy Castle ou o [Bouncy Castle FIPS](https://www.bouncycastle.org/about/bouncy-castle-fips-faq/) para atender a esse requisito. **Para obter ajuda na instalação e configuração do Bouncy Castle FIPS, consulte a [documentação do BC FIPS](https://www.bouncycastle.org/documentation/), especialmente os Guias **do Usuário** e a Política de Segurança.** PDFs
+ As versões anteriores do AWS Encryption SDK for Java usam a API de criptografia do Bouncy Castle para Java. Este requisito só é atendido por não FIPS Bouncy Castle.
Se você não tiver o Bouncy Castle, acesse [Baixar Bouncy Castle for Java para](https://bouncycastle.org/download/bouncy-castle-java/) baixar o arquivo do provedor que corresponde ao seu JDK. [Você também pode usar o [Apache Maven](https://maven.apache.org/) para obter o artefato para o provedor padrão do Bouncy Castle ([bcprov-ext-jdk15on](https://mvnrepository.com/artifact/org.bouncycastle/bcprov-ext-jdk15on)) ou o artefato para o Bouncy Castle FIPS (bc-fips).](https://mvnrepository.com/artifact/org.bouncycastle/bc-fips)

**AWS SDK para Java**  
Versão 3. *x* of the AWS Encryption SDK for Java requer o AWS SDK for Java 2.x, mesmo se você não usar AWS KMS chaveiros.  
Versão 2. *x* ou anterior do AWS Encryption SDK for Java não requer AWS SDK para Java o. No entanto, AWS SDK para Java é necessário usar [AWS Key Management Service](https://aws.amazon.com/kms/)(AWS KMS) como provedor de chave mestra. A partir da AWS Encryption SDK for Java versão 2.4.0, o AWS Encryption SDK for Java suporta as versões 1.x e 2.x do. AWS SDK para Java AWS Encryption SDK os códigos para AWS SDK para Java 1.x e 2.x são interoperáveis. Por exemplo, você pode criptografar dados com AWS Encryption SDK código compatível com AWS SDK para Java 1.x e descriptografá-los usando código compatível AWS SDK for Java 2.x (ou vice-versa). As versões AWS Encryption SDK for Java anteriores à 2.4.0 suportam apenas AWS SDK para Java 1.x. Para obter informações sobre como atualizar sua versão do AWS Encryption SDK, consulte[Migrando seu AWS Encryption SDK](migration.md).  
Ao atualizar seu AWS Encryption SDK for Java código de AWS SDK para Java 1.x para AWS SDK for Java 2.x, substitua as referências à [`AWSKMS`interface](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/kms/package-summary.html) em AWS SDK para Java 1.x por referências à [`KmsClient`interface](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/kms/package-summary.html) em. AWS SDK for Java 2.x O AWS Encryption SDK for Java não suporta a [`KmsAsyncClient`interface](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/kms/KmsAsyncClient.html). Além disso, atualize seu código para usar os objetos relacionados ao AWS KMS no namespace `kmssdkv2`, em vez do namespace `kms`.   
Para instalar o AWS SDK para Java, use o Apache Maven.   
+ Para [importar todo o AWS SDK para Java](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-project-maven.html#build-the-entire-sdk-into-your-project) como uma dependência, declare-o no arquivo `pom.xml`.
+ Para criar uma dependência somente para o AWS KMS módulo na AWS SDK para Java versão 1.x, siga as instruções para [especificar módulos específicos](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-project-maven.html#modules-dependencies) e defina o. `artifactId` `aws-java-sdk-kms`
+ Para criar uma dependência somente para o AWS KMS módulo na AWS SDK para Java versão 2.x, siga as instruções para [especificar](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-project-maven.html#modules-dependencies) módulos específicos. Defina o `groupId` como `software.amazon.awssdk` e `artifactId` como `kms`.
Para ver mais mudanças, consulte [O que há de diferente entre a AWS SDK para Java versão 1.x e a 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/migration-whats-different.html) no Guia do AWS SDK for Java 2.x desenvolvedor.  
Os exemplos de Java no Guia do AWS Encryption SDK Desenvolvedor usam AWS SDK for Java 2.x o.

## Instalação
<a name="java-installation"></a>

Instalar a versão mais recente do AWS Encryption SDK for Java.

**nota**  
Todas as versões AWS Encryption SDK for Java anteriores à 2.0.0 estão em [end-of-supportfase](https://docs.aws.amazon.com/sdkref/latest/guide/maint-policy.html#version-life-cycle).  
Você pode atualizar com segurança a partir da versão 2.0.*x* e posteriores até a versão mais recente do AWS Encryption SDK for Java sem realizar alterações no código ou nos dados. No entanto, os [novos atributos de segurança](about-versions.md#version-2) introduzidos na versão 2.0.*x* não são compatíveis com versões anteriores. Para atualizar a partir de versões anteriores à 1.7.*x* até a versão 2.0. *x* e posteriores, primeiro será necessário atualizar para a versão 1.*x* mais recente do AWS Encryption SDK. Para obter detalhes, consulte [Migrando seu AWS Encryption SDK](migration.md).

Você pode instalar o AWS Encryption SDK for Java das seguintes maneiras.

**Manualmente**  
Para instalar o AWS Encryption SDK for Java, clone ou baixe o [aws-encryption-sdk-java](https://github.com/aws/aws-encryption-sdk-java/) GitHubrepositório.

**Uso do Apache Maven**  
O AWS Encryption SDK for Java está disponível por meio do [Apache Maven](https://maven.apache.org/) com a seguinte definição de dependência.  

```
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-encryption-sdk-java</artifactId>
  <version>3.0.0</version>
</dependency>
```

Depois de instalar o SDK, comece examinando o [exemplo de código Java](java-example-code.md) neste guia e o [Javadoc](https://aws.github.io/aws-encryption-sdk-java/) ativado. GitHub

# AWS Encryption SDK for Java exemplos
<a name="java-example-code"></a>

Os exemplos a seguir mostram como usar o para AWS Encryption SDK for Java criptografar e descriptografar dados. Esses exemplos mostram como usar a versão 3. *x* e posterior do AWS Encryption SDK for Java. Versão 3. *x* do AWS Encryption SDK for Java requer AWS SDK for Java 2.x o. Versão 3. *x* do AWS Encryption SDK for Java substitui os [fornecedores de chaves mestras](concepts.md#master-key-provider) por [chaveiros](concepts.md#keyring). Para exemplos que usam versões anteriores, encontre sua versão na lista de [lançamentos](https://github.com/aws/aws-encryption-sdk-java/releases) do [aws-encryption-sdk-java](https://github.com/aws/aws-encryption-sdk-java/)repositório em GitHub.

**Topics**
+ [Strings](#java-example-strings)
+ [streams de bytes](#java-example-streams)
+ [Fluxos de bytes com vários provedores de chaves mestres](#java-example-multiple-providers)

## Criptografar e descriptografar strings
<a name="java-example-strings"></a>

O exemplo a seguir mostra como usar a versão 3. *x* do AWS Encryption SDK for Java para criptografar e descriptografar strings. Antes de usar a string, converta-a em uma matriz de bytes.

Este exemplo usa um [AWS KMS chaveiro.](use-kms-keyring.md) Ao criptografar com um AWS KMS chaveiro, você pode usar um ID de chave, ARN de chave, nome de alias ou ARN de alias para identificar as chaves KMS. Ao descriptografar, você deve usar um ARN de chave para identificar as chaves KMS.

Quando você chama o método `encryptData()`, ele retorna uma [mensagem criptografada](concepts.md#message) (`CryptoResult`) que inclui o texto cifrado, as chaves de dados criptografadas e o contexto de criptografia. Quando você chama `getResult` no objeto `CryptoResult`, ele retorna uma versão de cadeia codificada em base 64 da [mensagem criptografada](message-format.md) que você pode passar para o método `decryptData()`.

Da mesma forma, quando você chama`decryptData()`, o `CryptoResult` objeto que ele retorna contém a mensagem de texto sem formatação e um AWS KMS key ID. Antes que seu aplicativo retorne o texto sem formatação, verifique se o AWS KMS key ID e o contexto de criptografia na mensagem criptografada são os que você espera.

```
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package com.amazonaws.crypto.keyrings;

import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CommitmentPolicy;
import com.amazonaws.encryptionsdk.CryptoResult;
import software.amazon.cryptography.materialproviders.IKeyring;
import software.amazon.cryptography.materialproviders.MaterialProviders;
import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMultiKeyringInput;
import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

/**
 * Encrypts and then decrypts data using an AWS KMS Keyring.
 *
 * <p>Arguments:
 *
 * <ol>
 *   <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master
 *       key (CMK), see 'Viewing Keys' at
 *       http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html
 * </ol>
 */
public class BasicEncryptionKeyringExample {

  private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8);

  public static void main(final String[] args) {
    final String keyArn = args[0];

    encryptAndDecryptWithKeyring(keyArn);
  }

  public static void encryptAndDecryptWithKeyring(final String keyArn) {
    // 1. Instantiate the SDK
    // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy,
    // which means this client only encrypts using committing algorithm suites and enforces
    // that the client will only decrypt encrypted messages that were created with a committing
    // algorithm suite.
    // This is the default commitment policy if you build the client with
    // `AwsCrypto.builder().build()`
    // or `AwsCrypto.standard()`.
    final AwsCrypto crypto =
        AwsCrypto.builder()
            .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt)
            .build();

    // 2. Create the AWS KMS keyring.
    // This example creates a multi keyring, which automatically creates the KMS client.
    final MaterialProviders materialProviders =
        MaterialProviders.builder()
            .MaterialProvidersConfig(MaterialProvidersConfig.builder().build())
            .build();
    final CreateAwsKmsMultiKeyringInput keyringInput =
        CreateAwsKmsMultiKeyringInput.builder().generator(keyArn).build();
    final IKeyring kmsKeyring = materialProviders.CreateAwsKmsMultiKeyring(keyringInput);

    // 3. Create an encryption context
    // We recommend using an encryption context whenever possible
    // to protect integrity. This sample uses placeholder values.
    // For more information see:
    // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management
    final Map<String, String> encryptionContext =
        Collections.singletonMap("ExampleContextKey", "ExampleContextValue");

    // 4. Encrypt the data
    final CryptoResult<byte[], ?> encryptResult =
        crypto.encryptData(kmsKeyring, EXAMPLE_DATA, encryptionContext);
    final byte[] ciphertext = encryptResult.getResult();

    // 5. Decrypt the data
    final CryptoResult<byte[], ?> decryptResult =
        crypto.decryptData(
            kmsKeyring,
            ciphertext,
            // Verify that the encryption context in the result contains the
            // encryption context supplied to the encryptData method
            encryptionContext);

    // 6. Verify that the decrypted plaintext matches the original plaintext
    assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA);
  }
}
```

## Criptografar e descriptografar streams de bytes
<a name="java-example-streams"></a>

O exemplo a seguir mostra como usar o para AWS Encryption SDK criptografar e descriptografar fluxos de bytes.

Este exemplo usa um [chaveiro AES bruto](use-raw-aes-keyring.md).

Ao criptografar, o método `AwsCrypto.builder() .withEncryptionAlgorithm()` é usado para especificar um conjunto de algoritmos sem [assinaturas digitais](concepts.md#digital-sigs). Ao descriptografar, para garantir que o texto cifrado não esteja assinado, este exemplo usa o método `createUnsignedMessageDecryptingStream()`. O `createUnsignedMessageDecryptingStream()` método falhará se encontrar um texto cifrado com uma assinatura digital. 

Se você estiver criptografando com o conjunto de algoritmos padrão, que inclui assinaturas digitais, use o método `createDecryptingStream()` em seu lugar, conforme mostrado no próximo exemplo.

```
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package com.amazonaws.crypto.keyrings;

import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CommitmentPolicy;
import com.amazonaws.encryptionsdk.CryptoAlgorithm;
import com.amazonaws.encryptionsdk.CryptoInputStream;
import com.amazonaws.encryptionsdk.jce.JceMasterKey;
import com.amazonaws.util.IOUtils;
import software.amazon.cryptography.materialproviders.IKeyring;
import software.amazon.cryptography.materialproviders.MaterialProviders;
import software.amazon.cryptography.materialproviders.model.AesWrappingAlg;
import software.amazon.cryptography.materialproviders.model.CreateRawAesKeyringInput;
import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 * <p>
 * Encrypts and then decrypts a file under a random key.
 *
 * <p>
 * Arguments:
 * <ol>
 * <li>Name of file containing plaintext data to encrypt
 * </ol>
 *
 * <p>
 * This program demonstrates using a standard Java {@link SecretKey} object as a {@link IKeyring} to
 * encrypt and decrypt streaming data.
 */
public class FileStreamingKeyringExample {
    private static String srcFile;

    public static void main(String[] args) throws IOException {
        srcFile = args[0];

        // In this example, we generate a random key. In practice, 
        // you would get a key from an existing store
        SecretKey cryptoKey = retrieveEncryptionKey();

        // Create a Raw Aes Keyring using the random key and an AES-GCM encryption algorithm
        final MaterialProviders materialProviders = MaterialProviders.builder()
                .MaterialProvidersConfig(MaterialProvidersConfig.builder().build())
                .build();
        final CreateRawAesKeyringInput keyringInput = CreateRawAesKeyringInput.builder()
                .wrappingKey(ByteBuffer.wrap(cryptoKey.getEncoded()))
                .keyNamespace("Example")
                .keyName("RandomKey")
                .wrappingAlg(AesWrappingAlg.ALG_AES128_GCM_IV12_TAG16)
                .build();
        IKeyring keyring = materialProviders.CreateRawAesKeyring(keyringInput);

        // Instantiate the SDK.
        // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy,
        // which means this client only encrypts using committing algorithm suites and enforces
        // that the client will only decrypt encrypted messages that were created with a committing
        // algorithm suite.
        // This is the default commitment policy if you build the client with
        // `AwsCrypto.builder().build()`
        // or `AwsCrypto.standard()`.
        // This example encrypts with an algorithm suite that doesn't include signing for faster decryption,
        // since this use case assumes that the contexts that encrypt and decrypt are equally trusted.
        final AwsCrypto crypto = AwsCrypto.builder()
                .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt)
                .withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY)
                .build();

        // Create an encryption context to identify the ciphertext
        Map<String, String> context = Collections.singletonMap("Example", "FileStreaming");

        // Because the file might be too large to load into memory, we stream the data, instead of 
        //loading it all at once.
        FileInputStream in = new FileInputStream(srcFile);
        CryptoInputStream<JceMasterKey> encryptingStream = crypto.createEncryptingStream(keyring, in, context);

        FileOutputStream out = new FileOutputStream(srcFile + ".encrypted");
        IOUtils.copy(encryptingStream, out);
        encryptingStream.close();
        out.close();

        // Decrypt the file. Verify the encryption context before returning the plaintext.
        // Since the data was encrypted using an unsigned algorithm suite, use the recommended
        // createUnsignedMessageDecryptingStream method, which only accepts unsigned messages.
        in = new FileInputStream(srcFile + ".encrypted");
        CryptoInputStream<JceMasterKey> decryptingStream = crypto.createUnsignedMessageDecryptingStream(keyring, in);
        // Does it contain the expected encryption context?
        if (!"FileStreaming".equals(decryptingStream.getCryptoResult().getEncryptionContext().get("Example"))) {
            throw new IllegalStateException("Bad encryption context");
        }

        // Write the plaintext data to disk.
        out = new FileOutputStream(srcFile + ".decrypted");
        IOUtils.copy(decryptingStream, out);
        decryptingStream.close();
        out.close();
    }

    /**
     * In practice, this key would be saved in a secure location.
     * For this demo, we generate a new random key for each operation.
     */
    private static SecretKey retrieveEncryptionKey() {
        SecureRandom rnd = new SecureRandom();
        byte[] rawKey = new byte[16]; // 128 bits
        rnd.nextBytes(rawKey);
        return new SecretKeySpec(rawKey, "AES");
    }
}
```

## Criptografando e descriptografando fluxos de bytes com um chaveiro múltiplo
<a name="java-example-multiple-providers"></a>

O exemplo a seguir mostra como usar o AWS Encryption SDK com um [chaveiro múltiplo](use-multi-keyring.md). Quando você usa um multitoken de autenticação para criptografar dados, qualquer uma das chaves de empacotamento em qualquer um de seus tokens de autenticação pode descriptografar esses dados. Este exemplo usa um [AWS KMS chaveiro e um chaveiro](use-kms-keyring.md) [RSA bruto como chaveiros](use-raw-rsa-keyring.md) secundários.

Este exemplo criptografa com o [pacote de algoritmos padrão](supported-algorithms.md), que inclui uma [assinatura digital](concepts.md#digital-sigs). Durante o streaming, ele AWS Encryption SDK libera texto sem formatação após as verificações de integridade, mas antes de verificar a assinatura digital. Para evitar o uso do texto simples até que a assinatura seja verificada, este exemplo armazena o texto simples em buffer e o grava no disco somente após a conclusão da descriptografia e da verificação. 

```
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

package com.amazonaws.crypto.keyrings;

import com.amazonaws.encryptionsdk.AwsCrypto;
import com.amazonaws.encryptionsdk.CommitmentPolicy;
import com.amazonaws.encryptionsdk.CryptoOutputStream;
import com.amazonaws.util.IOUtils;
import software.amazon.cryptography.materialproviders.IKeyring;
import software.amazon.cryptography.materialproviders.MaterialProviders;
import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMultiKeyringInput;
import software.amazon.cryptography.materialproviders.model.CreateMultiKeyringInput;
import software.amazon.cryptography.materialproviders.model.CreateRawRsaKeyringInput;
import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig;
import software.amazon.cryptography.materialproviders.model.PaddingScheme;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Collections;

/**
 * <p>
 * Encrypts a file using both AWS KMS Key and an asymmetric key pair.
 *
 * <p>
 * Arguments:
 * <ol>
 * <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS key,
 *   see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html
 *
 * <li>Name of file containing plaintext data to encrypt
 * </ol>
 * <p>
 * You might use AWS Key Management Service (AWS KMS) for most encryption and decryption operations, but
 * still want the option of decrypting your data offline independently of AWS KMS. This sample
 * demonstrates one way to do this.
 * <p>
 * The sample encrypts data under both an AWS KMS key and an "escrowed" RSA key pair
 * so that either key alone can decrypt it. You might commonly use the AWS KMS key for decryption. However,
 * at any time, you can use the private RSA key to decrypt the ciphertext independent of AWS KMS.
 * <p>
 * This sample uses the RawRsaKeyring to generate a RSA public-private key pair
 * and saves the key pair in memory. In practice, you would store the private key in a secure offline
 * location, such as an offline HSM, and distribute the public key to your development team.
 */
public class EscrowedEncryptKeyringExample {
    private static ByteBuffer publicEscrowKey;
    private static ByteBuffer privateEscrowKey;

    public static void main(final String[] args) throws Exception {
        // This sample generates a new random key for each operation.
        // In practice, you would distribute the public key and save the private key in secure
        // storage.
        generateEscrowKeyPair();

        final String kmsArn = args[0];
        final String fileName = args[1];

        standardEncrypt(kmsArn, fileName);
        standardDecrypt(kmsArn, fileName);

        escrowDecrypt(fileName);
    }

    private static void standardEncrypt(final String kmsArn, final String fileName) throws Exception {
        // Encrypt with the KMS key and the escrowed public key
        // 1. Instantiate the SDK
        // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy,
        // which means this client only encrypts using committing algorithm suites and enforces
        // that the client will only decrypt encrypted messages that were created with a committing
        // algorithm suite.
        // This is the default commitment policy if you build the client with
        // `AwsCrypto.builder().build()`
        // or `AwsCrypto.standard()`.
        final AwsCrypto crypto = AwsCrypto.builder()
                .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt)
                .build();

        // 2. Create the AWS KMS keyring.
        // This example creates a multi keyring, which automatically creates the KMS client.
        final MaterialProviders matProv = MaterialProviders.builder()
                .MaterialProvidersConfig(MaterialProvidersConfig.builder().build())
                .build();
        final CreateAwsKmsMultiKeyringInput keyringInput = CreateAwsKmsMultiKeyringInput.builder()
                .generator(kmsArn)
                .build();
        IKeyring kmsKeyring = matProv.CreateAwsKmsMultiKeyring(keyringInput);

        // 3. Create the Raw Rsa Keyring with Public Key.
        final CreateRawRsaKeyringInput encryptingKeyringInput = CreateRawRsaKeyringInput.builder()
                .keyName("Escrow")
                .keyNamespace("Escrow")
                .paddingScheme(PaddingScheme.OAEP_SHA512_MGF1)
                .publicKey(publicEscrowKey)
                .build();
        IKeyring rsaPublicKeyring = matProv.CreateRawRsaKeyring(encryptingKeyringInput);

        // 4. Create the multi-keyring.
        final CreateMultiKeyringInput createMultiKeyringInput = CreateMultiKeyringInput.builder()
                .generator(kmsKeyring)
                .childKeyrings(Collections.singletonList(rsaPublicKeyring))
                .build();
        IKeyring multiKeyring = matProv.CreateMultiKeyring(createMultiKeyringInput);

        // 5. Encrypt the file
        // To simplify this code example, we omit the encryption context. Production code should always 
        // use an encryption context. 
        final FileInputStream in = new FileInputStream(fileName);
        final FileOutputStream out = new FileOutputStream(fileName + ".encrypted");
        final CryptoOutputStream<?> encryptingStream = crypto.createEncryptingStream(multiKeyring, out);

        IOUtils.copy(in, encryptingStream);
        in.close();
        encryptingStream.close();
    }

    private static void standardDecrypt(final String kmsArn, final String fileName) throws Exception {
        // Decrypt with the AWS KMS key and the escrow public key. 

        // 1. Instantiate the SDK.
        // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy,
        // which means this client only encrypts using committing algorithm suites and enforces
        // that the client will only decrypt encrypted messages that were created with a committing
        // algorithm suite.
        // This is the default commitment policy if you build the client with
        // `AwsCrypto.builder().build()`
        // or `AwsCrypto.standard()`.
        final AwsCrypto crypto = AwsCrypto.builder()
                .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt)
                .build();

        // 2. Create the AWS KMS keyring.
        // This example creates a multi keyring, which automatically creates the KMS client.
        final MaterialProviders matProv = MaterialProviders.builder()
                .MaterialProvidersConfig(MaterialProvidersConfig.builder().build())
                .build();
        final CreateAwsKmsMultiKeyringInput keyringInput = CreateAwsKmsMultiKeyringInput.builder()
                .generator(kmsArn)
                .build();
        IKeyring kmsKeyring = matProv.CreateAwsKmsMultiKeyring(keyringInput);

        // 3. Create the Raw Rsa Keyring with Public Key.
        final CreateRawRsaKeyringInput encryptingKeyringInput = CreateRawRsaKeyringInput.builder()
                .keyName("Escrow")
                .keyNamespace("Escrow")
                .paddingScheme(PaddingScheme.OAEP_SHA512_MGF1)
                .publicKey(publicEscrowKey)
                .build();
        IKeyring rsaPublicKeyring = matProv.CreateRawRsaKeyring(encryptingKeyringInput);

        // 4. Create the multi-keyring.
        final CreateMultiKeyringInput createMultiKeyringInput = CreateMultiKeyringInput.builder()
                .generator(kmsKeyring)
                .childKeyrings(Collections.singletonList(rsaPublicKeyring))
                .build();
        IKeyring multiKeyring = matProv.CreateMultiKeyring(createMultiKeyringInput);

        // 5. Decrypt the file
        // To simplify this code example, we omit the encryption context. Production code should always 
        // use an encryption context. 
        final FileInputStream in = new FileInputStream(fileName + ".encrypted");
        final FileOutputStream out = new FileOutputStream(fileName + ".decrypted");
        // Since we are using a signing algorithm suite, we avoid streaming decryption directly to the output file,
        // to ensure that the trailing signature is verified before writing any untrusted plaintext to disk.
        final ByteArrayOutputStream plaintextBuffer = new ByteArrayOutputStream();
        final CryptoOutputStream<?> decryptingStream = crypto.createDecryptingStream(multiKeyring, plaintextBuffer);
        IOUtils.copy(in, decryptingStream);
        in.close();
        decryptingStream.close();
        final ByteArrayInputStream plaintextReader = new ByteArrayInputStream(plaintextBuffer.toByteArray());
        IOUtils.copy(plaintextReader, out);
        out.close();
    }

    private static void escrowDecrypt(final String fileName) throws Exception {
        // You can decrypt the stream using only the private key.
        // This method does not call AWS KMS.

        // 1. Instantiate the SDK
        final AwsCrypto crypto = AwsCrypto.standard();

        // 2. Create the Raw Rsa Keyring with Private Key.
        final MaterialProviders matProv = MaterialProviders.builder()
                .MaterialProvidersConfig(MaterialProvidersConfig.builder().build())
                .build();
        final CreateRawRsaKeyringInput encryptingKeyringInput = CreateRawRsaKeyringInput.builder()
                .keyName("Escrow")
                .keyNamespace("Escrow")
                .paddingScheme(PaddingScheme.OAEP_SHA512_MGF1)
                .publicKey(publicEscrowKey)
                .privateKey(privateEscrowKey)
                .build();
        IKeyring escrowPrivateKeyring = matProv.CreateRawRsaKeyring(encryptingKeyringInput);


        // 3. Decrypt the file
        // To simplify this code example, we omit the encryption context. Production code should always 
        // use an encryption context. 
        final FileInputStream in = new FileInputStream(fileName + ".encrypted");
        final FileOutputStream out = new FileOutputStream(fileName + ".deescrowed");
        final CryptoOutputStream<?> decryptingStream = crypto.createDecryptingStream(escrowPrivateKeyring, out);
        IOUtils.copy(in, decryptingStream);
        in.close();
        decryptingStream.close();

    }

    private static void generateEscrowKeyPair() throws GeneralSecurityException {
        final KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
        kg.initialize(4096); // Escrow keys should be very strong
        final KeyPair keyPair = kg.generateKeyPair();
        publicEscrowKey = RawRsaKeyringExample.getPEMPublicKey(keyPair.getPublic());
        privateEscrowKey = RawRsaKeyringExample.getPEMPrivateKey(keyPair.getPrivate());

    }
}
```