

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# SDK di crittografia AWS per Java
<a name="java"></a>

In questo argomento viene descritto come installare e utilizzare SDK di crittografia AWS per Java. Per dettagli sulla programmazione con SDK di crittografia AWS per Java, consulta il [aws-encryption-sdk-java](https://github.com/aws/aws-encryption-sdk-java/)repository su GitHub. Per la documentazione sulle API, consulta [Javadoc](https://aws.github.io/aws-encryption-sdk-java/) per il SDK di crittografia AWS per Java.

**Topics**
+ [

## Prerequisiti
](#java-prerequisites)
+ [

## Installazione
](#java-installation)
+ [Esempi](java-example-code.md)

## Prerequisiti
<a name="java-prerequisites"></a>

Prima di installare il SDK di crittografia AWS per Java, assicuratevi di avere i seguenti prerequisiti.

**Un ambiente di sviluppo Java**  
È necessario Java 8 o versioni successive. Nel sito Web di Oracle, accedi alla pagina [Java SE Download](https://www.oracle.com/java/technologies/downloads/), quindi scarica e installa Java SE Development Kit (JDK).  
Se utilizzi Oracle JDK, devi scaricare e installare anche [Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files](http://www.oracle.com/java/technologies/javase-jce8-downloads.html).

**Bouncy Castle**  
 SDK di crittografia AWS per Java Richiede [Bouncy](https://www.bouncycastle.org/download/bouncy-castle-java/) Castle.   
+ SDK di crittografia AWS per Java le versioni 1.6.1 e successive utilizzano Bouncy Castle per serializzare e deserializzare oggetti crittografici. Puoi usare Bouncy Castle o [Bouncy Castle FIPS](https://www.bouncycastle.org/about/bouncy-castle-fips-faq/) per soddisfare questo requisito. [https://www.bouncycastle.org/documentation/](https://www.bouncycastle.org/documentation/) PDFs
+ Le versioni precedenti SDK di crittografia AWS per Java utilizzano l'API di crittografia di Bouncy Castle per Java. Questo requisito è soddisfatto solo da Bouncy Castle non FIPS.
Se non hai Bouncy Castle, vai a [Scarica Bouncy Castle per Java per scaricare il file del provider che corrisponde](https://bouncycastle.org/download/bouncy-castle-java/) al tuo JDK. [https://mvnrepository.com/artifact/org.bouncycastle/bcprov-ext-jdk15on](https://mvnrepository.com/artifact/org.bouncycastle/bcprov-ext-jdk15on)

**AWS SDK per Java**  
Versione 3. *x* of the SDK di crittografia AWS per Java richiede AWS SDK for Java 2.x, anche se non si utilizzano AWS KMS portachiavi.  
Versione 2. *x* o precedente di SDK di crittografia AWS per Java non richiede AWS SDK per Java. Tuttavia, AWS SDK per Java è necessario utilizzare [AWS Key Management Service](https://aws.amazon.com/kms/)(AWS KMS) come fornitore di chiavi principali. A partire dalla SDK di crittografia AWS per Java versione 2.4.0, SDK di crittografia AWS per Java supporta sia la versione 1.x che la 2.x di. AWS SDK per Java AWS Encryption SDK il codice per AWS SDK per Java 1.x e 2.x è interoperabile. Ad esempio, è possibile crittografare i dati con AWS Encryption SDK codice che supporta AWS SDK per Java 1.x e decrittografarli utilizzando codice che supporta (o viceversa). AWS SDK for Java 2.x Le versioni precedenti alla 2.4.0 supportano SDK di crittografia AWS per Java solo la versione 1.x. AWS SDK per Java Per informazioni sull'aggiornamento della versione di in uso AWS Encryption SDK, vedere. [Migrazione del tuo AWS Encryption SDK](migration.md)  
Quando aggiorni il SDK di crittografia AWS per Java codice dalla versione AWS SDK per Java 1.x alla versione 1.x AWS SDK for Java 2.x, sostituisci i riferimenti all'[`AWSKMS`interfaccia](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/kms/package-summary.html) nella versione AWS SDK per Java 1.x con i riferimenti all'[`KmsClient`interfaccia](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/kms/package-summary.html) in. AWS SDK for Java 2.x[Non SDK di crittografia AWS per Java supporta l'interfaccia. `KmsAsyncClient`](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/kms/KmsAsyncClient.html) Inoltre, aggiorna il codice per utilizzare gli oggetti AWS KMS correlati allo spazio dei `kmssdkv2` nomi nel namespace, anziché nel namespace. `kms`   
Per installare, usa Apache Maven AWS SDK per Java.   
+ Per [importare l'intero AWS SDK per Java](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-project-maven.html#build-the-entire-sdk-into-your-project) come dipendenza, dichiaralo nel file `pom.xml`.
+ Per creare una dipendenza solo per il AWS KMS modulo in AWS SDK per Java 1.x, segui le istruzioni per [specificare moduli particolari](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-project-maven.html#modules-dependencies) e imposta il valore su. `artifactId` `aws-java-sdk-kms`
+ [Per creare una dipendenza solo per il AWS KMS modulo in AWS SDK per Java 2.x, segui le istruzioni per specificare moduli particolari.](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-project-maven.html#modules-dependencies) Imposta il `groupId` to `software.amazon.awssdk` e il to. `artifactId` `kms`
Per ulteriori modifiche, consulta [Cosa c'è di diverso tra AWS SDK per Java 1.x e 2.x nella Guida](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/migration-whats-different.html) per gli AWS SDK for Java 2.x sviluppatori.  
Gli esempi di Java nella AWS Encryption SDK Developer Guide utilizzano il. AWS SDK for Java 2.x

## Installazione
<a name="java-installation"></a>

Installazione della versione più recente della SDK di crittografia AWS per Java.

**Nota**  
[Tutte le versioni SDK di crittografia AWS per Java precedenti alla 2.0.0 sono in fase di sviluppo. end-of-support](https://docs.aws.amazon.com/sdkref/latest/guide/maint-policy.html#version-life-cycle)  
È possibile eseguire l'aggiornamento in tutta sicurezza dalla versione 2.0. *x* e versioni successive alla versione più recente di SDK di crittografia AWS per Java senza modifiche al codice o ai dati. Tuttavia, nella versione 2.0 sono state introdotte [nuove funzionalità di sicurezza](about-versions.md#version-2). *x* non sono retrocompatibili. Per eseguire l'aggiornamento da versioni precedenti alla 1.7. *x* alla versione 2.0. *x* e versioni successive, è necessario prima eseguire l'aggiornamento alla versione più recente 1. versione *x* di AWS Encryption SDK. Per informazioni dettagliate, vedi [Migrazione del tuo AWS Encryption SDK](migration.md).

È possibile installarlo SDK di crittografia AWS per Java nei seguenti modi.

**Manualmente**  
Per installare SDK di crittografia AWS per Java, clona o scarica il [aws-encryption-sdk-java](https://github.com/aws/aws-encryption-sdk-java/) GitHubrepository.

**Utilizzo di Apache Maven**  
 SDK di crittografia AWS per Java è disponibile tramite [Apache Maven](https://maven.apache.org/) con la seguente definizione di dipendenza.  

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

[Dopo aver installato l'SDK, inizia a guardare il [codice Java di esempio](java-example-code.md) in questa guida e Javadoc attivo. GitHub](https://aws.github.io/aws-encryption-sdk-java/)

# SDK di crittografia AWS per Java esempi
<a name="java-example-code"></a>

Gli esempi seguenti mostrano come utilizzare il per SDK di crittografia AWS per Java crittografare e decrittografare i dati. Questi esempi mostrano come utilizzare la versione 3. *x* e versioni successive di SDK di crittografia AWS per Java. Versione 3. *x* of the SDK di crittografia AWS per Java richiede il AWS SDK for Java 2.x. Versione 3. *x* of the SDK di crittografia AWS per Java sostituisce i [fornitori di chiavi principali](concepts.md#master-key-provider) con [portachiavi](concepts.md#keyring). Per gli esempi che utilizzano versioni precedenti, trova la tua versione nell'elenco delle [versioni](https://github.com/aws/aws-encryption-sdk-java/releases) del [aws-encryption-sdk-java](https://github.com/aws/aws-encryption-sdk-java/)repository su. GitHub

**Topics**
+ [Stringhe](#java-example-strings)
+ [Flussi di byte](#java-example-streams)
+ [Stream di byte con più fornitori di chiavi master](#java-example-multiple-providers)

## Crittografia e decrittazione di stringhe
<a name="java-example-strings"></a>

L'esempio seguente mostra come utilizzare la versione 3. *x* delle stringhe SDK di crittografia AWS per Java per crittografare e decrittografare. Prima di utilizzare la stringa, convertirla in un matrice di byte.

[Questo esempio utilizza un portachiavi.AWS KMS](use-kms-keyring.md) Quando si esegue la crittografia con un AWS KMS portachiavi, è possibile utilizzare un ID chiave, un ARN della chiave, un nome alias o un alias ARN per identificare le chiavi KMS. Durante la decrittografia, è necessario utilizzare una chiave ARN per identificare le chiavi KMS.

Quando chiami il metodo `encryptData()` viene restituito un [messaggio crittografato](concepts.md#message) (`CryptoResult`) che include il testo cifrato, le chiavi dati crittografate e il contesto di crittografia. Quando chiama `getResult` sull'oggetto `CryptoResult`, viene restituita una versione di stringa codificata in base 64 del [messaggio crittografato](message-format.md) che puoi passare al metodo `decryptData()`.

Allo stesso modo, quando si chiama`decryptData()`, l'`CryptoResult`oggetto restituito contiene il messaggio in chiaro e un ID. AWS KMS key Prima che l'applicazione restituisca il testo non crittografato, verificate che l' AWS KMS key ID e il contesto di crittografia nel messaggio crittografato siano quelli previsti.

```
// 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);
  }
}
```

## Crittografia e decrittazione di flussi di byte
<a name="java-example-streams"></a>

L'esempio seguente mostra come utilizzare il per crittografare e AWS Encryption SDK decrittografare i flussi di byte.

[Questo esempio utilizza un portachiavi Raw AES.](use-raw-aes-keyring.md)

Durante la crittografia, questo esempio utilizza il `AwsCrypto.builder() .withEncryptionAlgorithm()` metodo per specificare una suite di algoritmi senza firme [digitali](concepts.md#digital-sigs). Durante la decrittografia, per garantire che il testo cifrato non sia firmato, questo esempio utilizza il metodo. `createUnsignedMessageDecryptingStream()` Il `createUnsignedMessageDecryptingStream()` metodo fallisce se incontra un testo cifrato con una firma digitale. 

Se state eseguendo la crittografia con la suite di algoritmi predefinita, che include le firme digitali, utilizzate invece il `createDecryptingStream()` metodo, come illustrato nell'esempio seguente.

```
// 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");
    }
}
```

## Crittografia e decrittografia di flussi di byte con un portachiavi multiplo
<a name="java-example-multiple-providers"></a>

[L'esempio seguente mostra come utilizzare il AWS Encryption SDK con un portachiavi multiplo.](use-multi-keyring.md) Quando utilizzi un keyring multiplo per crittografare i dati, questi possono essere decrittati con le chiavi di wrapping contenute in qualsiasi keyring. Questo esempio utilizza un [AWS KMS portachiavi e un portachiavi](use-kms-keyring.md) [Raw RSA come portachiavi secondari.](use-raw-rsa-keyring.md)

[Questo esempio esegue la crittografia con la [suite di algoritmi predefinita](supported-algorithms.md), che include una firma digitale.](concepts.md#digital-sigs) Durante lo streaming, AWS Encryption SDK rilascia il testo non crittografato dopo i controlli di integrità, ma prima di aver verificato la firma digitale. Per evitare di utilizzare il testo non crittografato fino alla verifica della firma, questo esempio memorizza nel buffer il testo semplice e lo scrive su disco solo quando la decrittografia e la verifica sono complete. 

```
// 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());

    }
}
```