

A versão 4 (V4) do AWS SDK para .NET foi lançada\$1

Para obter informações sobre mudanças significativas e migrar seus aplicativos, consulte o [tópico de migração](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html).

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

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á.

# Usar o armazenamento para internet Amazon Simple Storage Service
<a name="s3-apis-intro"></a>

O AWS SDK para .NET suporta o [Amazon S3](https://aws.amazon.com/s3/), que é armazenamento para a Internet. Ele foi projetado para facilitar a computação de escala na web para os desenvolvedores.

## APIs
<a name="w2aac19c15c25b5"></a>

 AWS SDK para .NET Ele fornece APIs para clientes do Amazon S3. Eles APIs permitem que você trabalhe com recursos do Amazon S3, como buckets e itens. Para ver o conjunto completo de APIs para o Amazon S3, veja o seguinte:
+ [AWS SDK para .NET Referência da API](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/) (e vá até “Amazon.S3").
+ Documentação [Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

O Amazon S3 APIs é fornecido pelos seguintes pacotes: NuGet 
+ [AWSSDK.S3](https://www.nuget.org/packages/AWSSDK.S3)
+ [Amazon.Extensions.S3.Encryption](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

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

Antes de começar, verifique se você [configurou seu ambiente](net-dg-config.md) e [configurou seu projeto](configuring-the-sdk.md). Revise também as informações em [Uso da SDK](net-dg-sdk-features.md).

## Exemplos neste documento
<a name="s3-apis-examples"></a>

Os tópicos a seguir neste documento mostram como usar o AWS SDK para .NET para trabalhar com o Amazon S3.
+ [Usar chaves KMS para a criptografia do S3](kms-keys-s3-encryption.md)

## Exemplos em outros documentos
<a name="s3-apis-examples-other"></a>

Os links a seguir para o [Amazon S3 Developer Guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/) fornecem exemplos adicionais de como usar o AWS SDK para .NET para trabalhar com o Amazon S3.

**nota**  
Embora esses exemplos e considerações adicionais de programação tenham sido criados para a versão 3 do AWS SDK para .NET uso do.NET Framework, eles também são viáveis para versões posteriores do AWS SDK para .NET uso do.NET Core. Às vezes, pequenos ajustes no código são necessários.

**Exemplos de programação do Amazon S3**
+  [Gerenciando ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-dot-net-sdk.html) 
+  [Criação de um bucket](https://docs.aws.amazon.com/AmazonS3/latest/dev/create-bucket-get-location-example.html#create-bucket-get-location-dotnet) 
+  [Upload de um objeto](https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpNET.html) 
+  [https://docs.aws.amazon.com/AmazonS3/latest/dev/usingHLmpuDotNet.html](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingHLmpuDotNet.html)) 
+  [Multipart Upload com a API de baixo nível](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingLLmpuDotNet.html) 
+  [Listar objetos](https://docs.aws.amazon.com/AmazonS3/latest/dev/list-obj-version-enabled-bucket.html#list-obj-version-enabled-bucket-sdk-examples) 
+  [Chaves de listagem](https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingNetSDK.html) 
+  [Obter um objeto](https://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingNetSDK.html) 
+  [Copiar um objeto](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingNetSDK.html) 
+  [Copiar um objeto com a API do Multipart Upload](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingLLNetMPUapi.html) 
+  [Exclusão de um objeto](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingOneObjectUsingNetSDK.html) 
+  [Excluir de vários objetos](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingNetSDK.html) 
+  [Restaurar um objeto](https://docs.aws.amazon.com/AmazonS3/latest/dev/restore-object-dotnet.html) 
+  [Configurar um bucket para notificações](https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html) 
+  [Gerenciar o ciclo de vida de um objeto](https://docs.aws.amazon.com/AmazonS3/latest/dev/manage-lifecycle-using-dot-net.html) 
+  [Gerenciar um URL de objeto pré-assinado](https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLDotNetSDK.html) 
+  [Gerenciamento de sites](https://docs.aws.amazon.com/AmazonS3/latest/dev/ConfigWebSiteDotNet.html) 
+  [Ativação do compartilhamento de recursos de origem cruzada (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/ManageCorsUsingDotNet.html) 

**Considerações adicionais sobre programação**
+  [Usar o AWS SDK para .NET para o Amazon S3 Programming](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingTheMPDotNetAPI.html) 
+  [Fazer solicitações usando as credenciais temporárias do usuário do IAM](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempSessionTokenDotNet.html) 
+  [Fazer solicitações usando as credenciais temporárias de usuário federado](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempFederationTokenDotNet.html) 
+  [Especificar a criptografia no lado do servidor](https://docs.aws.amazon.com/AmazonS3/latest/dev/SSEUsingDotNetSDK.html) 
+  [Especificar a criptografia do lado do servidor com chaves de criptografia fornecidas pelo cliente](https://docs.aws.amazon.com/AmazonS3/latest/dev/sse-c-using-dot-net-sdk.html) 

# Usando AWS KMS chaves para criptografia do Amazon S3 no AWS SDK para .NET
<a name="kms-keys-s3-encryption"></a>

Este exemplo mostra como usar AWS Key Management Service chaves para criptografar objetos do Amazon S3. O aplicativo cria uma chave mestra do cliente (CMK) e a usa para criar um objeto [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) para criptografia do lado do cliente. O aplicativo usa esse cliente para criar um objeto criptografado a partir de um determinado arquivo de texto em um bucket existente do Amazon S3. Em seguida, ele descriptografa o objeto e exibe seu conteúdo.

**Atenção**  
Uma classe similar chamada `AmazonS3EncryptionClient` está obsoleta e é menos segura do que a classe `AmazonS3EncryptionClientV2`. Para migrar o código existente que usa `AmazonS3EncryptionClient`, consulte [Migração do cliente de criptografia S3 (V1 para V2)](s3-encryption-migration-v1-v2.md).

**Topics**
+ [Criar materiais de criptografia](#kms-s3-enc-mat)
+ [Criar e criptografar um objeto do Amazon S3](#kms-s3-create-ojbect)
+ [Código completo](#kms-s3-complete-code)
+ [Considerações adicionais](#kms-s3-additional)

## Criar materiais de criptografia
<a name="kms-s3-enc-mat"></a>

O trecho a seguir cria um objeto `EncryptionMaterials` que contém uma ID de chave KMS.

O exemplo [no final deste tópico](#kms-s3-complete-code) mostra o snippet em uso.

```
      // Create a customer master key (CMK) and store the result
      CreateKeyResponse createKeyResponse =
        await new AmazonKeyManagementServiceClient().CreateKeyAsync(new CreateKeyRequest());
      var kmsEncryptionContext = new Dictionary<string, string>();
      var kmsEncryptionMaterials = new EncryptionMaterialsV2(
        createKeyResponse.KeyMetadata.KeyId, KmsType.KmsContext, kmsEncryptionContext);
```

## Criar e criptografar um objeto do Amazon S3
<a name="kms-s3-create-ojbect"></a>

O snippet a seguir cria um objeto `AmazonS3EncryptionClientV2` que usa os materiais de criptografia criados anteriormente. Em seguida, ele usa o cliente para criar e criptografar um novo objeto do Amazon S3.

O exemplo [no final deste tópico](#kms-s3-complete-code) mostra o snippet em uso.

```
    //
    // Method to create and encrypt an object in an S3 bucket
    static async Task<GetObjectResponse> CreateAndRetrieveObjectAsync(
      EncryptionMaterialsV2 materials, string bucketName,
      string fileName, string itemName)
    {
      // CryptoStorageMode.ObjectMetadata is required for KMS EncryptionMaterials
      var config = new AmazonS3CryptoConfigurationV2(SecurityProfile.V2AndLegacy)
      {
        StorageMode = CryptoStorageMode.ObjectMetadata
      };
      var s3EncClient = new AmazonS3EncryptionClientV2(config, materials);

      // Create, encrypt, and put the object
      await s3EncClient.PutObjectAsync(new PutObjectRequest
      {
        BucketName = bucketName,
        Key = itemName,
        ContentBody = File.ReadAllText(fileName)
      });

      // Get, decrypt, and return the object
      return await s3EncClient.GetObjectAsync(new GetObjectRequest
      {
        BucketName = bucketName,
        Key = itemName
      });
    }
```

## Código completo
<a name="kms-s3-complete-code"></a>

Esta seção mostra as referências relevantes e o código completo desse exemplo.

### Referências do SDK
<a name="w2aac19c15c25c13c15b5b1"></a>

NuGet pacotes:
+ [Amazon.Extensions.S3.Encryption](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

Elementos de programação:
+ Namespace [Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

  Classe [EncryptionClientAmazonS3](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) V2

  Classe [CryptoConfigurationAmazonS3](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3CryptoConfigurationV2.html) V2

  Classe [CryptoStorageMode](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.CryptoStorageMode.html)

  Classe [EncryptionMaterialsV2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.EncryptionMaterialsV2.html)
+ Namespace [Amazon.Extensions.S3.Encryption.Primitives](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.Primitives.html)

  Classe [KmsType](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.Primitives.KmsType.html)
+ Namespace [Amazon.S3.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/NS3Model.html)

  Classe [GetObjectRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TGetObjectRequest.html)

  Classe [GetObjectResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TGetObjectResponse.html)

  Classe [PutObjectRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TPutObjectRequest.html)
+ [Namespace Amazon. KeyManagementService](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/NKeyManagementService.html)

  Classe [AmazonKeyManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/TKeyManagementServiceClient.html)
+ [Namespace Amazon. KeyManagementService.Modelo](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/NKeyManagementServiceModel.html)

  Classe [CreateKeyRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/TCreateKeyRequest.html)

  Classe [CreateKeyResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/TCreateKeyResponse.html)

### O código
<a name="w2aac19c15c25c13c15b7b1"></a>

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Amazon.Extensions.S3.Encryption;
using Amazon.Extensions.S3.Encryption.Primitives;
using Amazon.S3.Model;
using Amazon.KeyManagementService;
using Amazon.KeyManagementService.Model;

namespace KmsS3Encryption
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to store text in an encrypted S3 object.
  class Program
  {
    private const int MaxArgs = 3;

    public static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if((parsedArgs.Count == 0) || (parsedArgs.Count > MaxArgs))
      {
        PrintHelp();
        return;
      }

      // Get the application arguments from the parsed list
      string bucketName =
        CommandLine.GetArgument(parsedArgs, null, "-b", "--bucket-name");
      string fileName =
        CommandLine.GetArgument(parsedArgs, null, "-f", "--file-name");
      string itemName =
        CommandLine.GetArgument(parsedArgs, null, "-i", "--item-name");
      if(string.IsNullOrEmpty(bucketName) || (string.IsNullOrEmpty(fileName)))
        CommandLine.ErrorExit(
          "\nOne or more of the required arguments is missing or incorrect." +
          "\nRun the command with no arguments to see help.");
      if(!File.Exists(fileName))
        CommandLine.ErrorExit($"\nThe given file {fileName} doesn't exist.");
      if(string.IsNullOrEmpty(itemName))
        itemName = Path.GetFileName(fileName);

      // Create a customer master key (CMK) and store the result
      CreateKeyResponse createKeyResponse =
        await new AmazonKeyManagementServiceClient().CreateKeyAsync(new CreateKeyRequest());
      var kmsEncryptionContext = new Dictionary<string, string>();
      var kmsEncryptionMaterials = new EncryptionMaterialsV2(
        createKeyResponse.KeyMetadata.KeyId, KmsType.KmsContext, kmsEncryptionContext);

      // Create the object in the bucket, then display the content of the object
      var putObjectResponse =
        await CreateAndRetrieveObjectAsync(kmsEncryptionMaterials, bucketName, fileName, itemName);
      Stream stream = putObjectResponse.ResponseStream;
      StreamReader reader = new StreamReader(stream);
      Console.WriteLine(reader.ReadToEnd());
    }


    //
    // Method to create and encrypt an object in an S3 bucket
    static async Task<GetObjectResponse> CreateAndRetrieveObjectAsync(
      EncryptionMaterialsV2 materials, string bucketName,
      string fileName, string itemName)
    {
      // CryptoStorageMode.ObjectMetadata is required for KMS EncryptionMaterials
      var config = new AmazonS3CryptoConfigurationV2(SecurityProfile.V2AndLegacy)
      {
        StorageMode = CryptoStorageMode.ObjectMetadata
      };
      var s3EncClient = new AmazonS3EncryptionClientV2(config, materials);

      // Create, encrypt, and put the object
      await s3EncClient.PutObjectAsync(new PutObjectRequest
      {
        BucketName = bucketName,
        Key = itemName,
        ContentBody = File.ReadAllText(fileName)
      });

      // Get, decrypt, and return the object
      return await s3EncClient.GetObjectAsync(new GetObjectRequest
      {
        BucketName = bucketName,
        Key = itemName
      });
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: KmsS3Encryption -b <bucket-name> -f <file-name> [-i <item-name>]" +
        "\n  -b, --bucket-name: The name of an existing S3 bucket." +
        "\n  -f, --file-name: The name of a text file with content to encrypt and store in S3." +
        "\n  -i, --item-name: The name you want to use for the item." +
        "\n      If item-name isn't given, file-name will be used.");
    }

  }

  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

## Considerações adicionais
<a name="kms-s3-additional"></a>
+ Você pode verificar os resultados desse exemplo. Para fazer isso, acesse o [console do Amazon S3](https://console.aws.amazon.com/s3) e abra o bucket que você forneceu à aplicação. Em seguida, encontre o novo objeto, baixe-o e abra-o em um editor de texto.
+ A classe [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) implementa a mesma interface da classe padrão. `AmazonS3Client` Isso facilita a portabilidade do código para a classe `AmazonS3EncryptionClientV2` de modo que a criptografia e a descriptografia ocorram automaticamente e de maneira transparente no cliente.
+ Uma vantagem de usar uma AWS KMS chave como chave mestra é que você não precisa armazenar e gerenciar suas próprias chaves mestras; isso é feito por AWS. Uma segunda vantagem é que a `AmazonS3EncryptionClientV2` classe do AWS SDK para .NET é interoperável com a `AmazonS3EncryptionClientV2` classe do. AWS SDK para Java Isso significa que você pode criptografar com o AWS SDK para Java e descriptografar com o AWS SDK para .NET e vice-versa.
**nota**  
A `AmazonS3EncryptionClientV2` classe do AWS SDK para .NET suporta chaves mestras do KMS somente quando executada no modo de metadados. O modo do arquivo de instruções da `AmazonS3EncryptionClientV2` classe do AWS SDK para .NET é incompatível com a `AmazonS3EncryptionClientV2` classe do AWS SDK para Java.
+ Para obter mais informações sobre a criptografia do lado do cliente com a `AmazonS3EncryptionClientV2` classe e como a criptografia de envelope funciona, consulte Criptografia de [dados do lado do cliente com o Amazon AWS SDK para .NET S3](https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/).