

La version 4 (V4) du AWS SDK pour .NET est sortie \$1

Pour plus d'informations sur les modifications majeures et la migration de vos applications, consultez la [rubrique relative à la migration](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)

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Utilisation du stockage sur Internet d'Amazon Simple Storage Service
<a name="s3-apis-intro"></a>

Il AWS SDK pour .NET prend en charge [Amazon S3](https://aws.amazon.com/s3/), qui est un stockage pour Internet. Il est conçu pour faciliter l'informatique à l'échelle d'Internet pour les développeurs.

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

Les AWS SDK pour .NET offres APIs pour les clients Amazon S3. Ils vous APIs permettent de travailler avec des ressources Amazon S3 telles que des compartiments et des articles. Pour consulter l'ensemble complet APIs de Amazon S3, consultez ce qui suit :
+ [AWS SDK pour .NET Référence d'API](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/) (et faites défiler la page jusqu'à « Amazon.S3 »).
+ [Amazon.Extensions.S3. Documentation sur](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html) le chiffrement

Les Amazon S3 APIs sont fournis par les NuGet packages suivants :
+ [AWSSDKS.3](https://www.nuget.org/packages/AWSSDK.S3)
+ [Amazon Extensions.S3. Chiffrement](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

## Conditions préalables
<a name="w2aac19c15c25b7"></a>

Avant de commencer, assurez-vous d'avoir [configuré votre environnement](net-dg-config.md) [et votre projet](configuring-the-sdk.md). Consultez également les informations contenues dans[Utilisation de l'SDK](net-dg-sdk-features.md).

## Exemples présentés dans ce document
<a name="s3-apis-examples"></a>

Les rubriques suivantes de ce document vous montrent comment utiliser le AWS SDK pour .NET pour travailler avec Amazon S3.
+ [Utilisation de clés KMS pour le chiffrement S3](kms-keys-s3-encryption.md)

## Exemples dans d'autres documents
<a name="s3-apis-examples-other"></a>

Les liens suivants vers le [guide du développeur Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/) fournissent des exemples supplémentaires de la façon d'utiliser le AWS SDK pour .NET pour travailler avec Amazon S3.

**Note**  
Bien que ces exemples et considérations de programmation supplémentaires aient été créés pour la AWS SDK pour .NET version 3 du .NET Framework, ils sont également viables pour les versions ultérieures AWS SDK pour .NET de .NET Core. De petits ajustements dans le code sont parfois nécessaires.

**Exemples de programmation Amazon S3**
+  [Gérer ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-dot-net-sdk.html) 
+  [Création d'un compartiment](https://docs.aws.amazon.com/AmazonS3/latest/dev/create-bucket-get-location-example.html#create-bucket-get-location-dotnet) 
+  [Chargement d'un objet](https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpNET.html) 
+  [Chargement en plusieurs parties avec l'API de haut niveau ([Amazon.S3.Transfer). TransferUtility](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/S3/TTransferUtility.html)](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingHLmpuDotNet.html)) 
+  [Chargement partitionné avec l'API de bas niveau](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingLLmpuDotNet.html) 
+  [Liste des objets](https://docs.aws.amazon.com/AmazonS3/latest/dev/list-obj-version-enabled-bucket.html#list-obj-version-enabled-bucket-sdk-examples) 
+  [Etablissement de la liste des clés](https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingNetSDK.html) 
+  [Obtention d'un objet](https://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingNetSDK.html) 
+  [Copie d'un objet](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingNetSDK.html) 
+  [Copie d'un objet grâce à l'API de chargement partitionné](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingLLNetMPUapi.html) 
+  [Suppression d'un objet](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingOneObjectUsingNetSDK.html) 
+  [Suppression de plusieurs objets](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingNetSDK.html) 
+  [Restauration d'un objet](https://docs.aws.amazon.com/AmazonS3/latest/dev/restore-object-dotnet.html) 
+  [Configuration des notifications d'un compartiment](https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html) 
+  [Gestion du cycle de vie d'un objet](https://docs.aws.amazon.com/AmazonS3/latest/dev/manage-lifecycle-using-dot-net.html) 
+  [Génération d'une URL d'objet présignée](https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLDotNetSDK.html) 
+  [Gestion de sites web](https://docs.aws.amazon.com/AmazonS3/latest/dev/ConfigWebSiteDotNet.html) 
+  [Activation du partage des ressources de plusieurs origines (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/ManageCorsUsingDotNet.html) 

**Considérations supplémentaires relatives à la programmation**
+  [Utilisation du AWS SDK pour .NET pour la programmation d'Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingTheMPDotNetAPI.html) 
+  [Demandes grâce aux informations d'identification temporaires de l'utilisateur IAM](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempSessionTokenDotNet.html) 
+  [Demandes grâce aux informations d'identification de sécurité temporaires de l'utilisateur fédéré](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempFederationTokenDotNet.html) 
+  [Spécification du chiffrement côté serveur](https://docs.aws.amazon.com/AmazonS3/latest/dev/SSEUsingDotNetSDK.html) 
+  [Spécification du chiffrement côté serveur avec clés de chiffrement fournies par le client](https://docs.aws.amazon.com/AmazonS3/latest/dev/sse-c-using-dot-net-sdk.html) 

# Utilisation de AWS KMS clés pour le chiffrement Amazon S3 dans AWS SDK pour .NET
<a name="kms-keys-s3-encryption"></a>

Cet exemple montre comment utiliser des AWS Key Management Service clés pour chiffrer des objets Amazon S3. L'application crée une clé principale client (CMK) et l'utilise pour créer un objet [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) pour le chiffrement côté client. L'application utilise ce client pour créer un objet chiffré à partir d'un fichier texte donné dans un compartiment Amazon S3 existant. Il déchiffre ensuite l'objet et affiche son contenu.

**Avertissement**  
Une classe similaire appelée `AmazonS3EncryptionClient` est obsolète et est moins sécurisée que la `AmazonS3EncryptionClientV2` classe. Pour migrer le code existant qui utilise`AmazonS3EncryptionClient`, voir[Migration du client de chiffrement S3 (V1 vers V2)](s3-encryption-migration-v1-v2.md).

**Topics**
+ [Création de matériel de chiffrement](#kms-s3-enc-mat)
+ [Création et chiffrement d'un objet Amazon S3](#kms-s3-create-ojbect)
+ [Code complet](#kms-s3-complete-code)
+ [Considérations supplémentaires](#kms-s3-additional)

## Création de matériel de chiffrement
<a name="kms-s3-enc-mat"></a>

L'extrait de code suivant crée un `EncryptionMaterials` objet contenant un ID de clé KMS.

L'exemple [à la fin de cette rubrique](#kms-s3-complete-code) montre cet extrait en cours d'utilisation.

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

## Création et chiffrement d'un objet Amazon S3
<a name="kms-s3-create-ojbect"></a>

L'extrait de code suivant crée un `AmazonS3EncryptionClientV2` objet qui utilise les matériaux de chiffrement créés précédemment. Il utilise ensuite le client pour créer et chiffrer un nouvel objet Amazon S3.

L'exemple [à la fin de cette rubrique](#kms-s3-complete-code) montre cet extrait en cours d'utilisation.

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

## Code complet
<a name="kms-s3-complete-code"></a>

Cette section présente les références pertinentes et le code complet de cet exemple.

### Références du SDK
<a name="w2aac19c15c25c13c15b5b1"></a>

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

Éléments de programmation :
+ [Espace de noms Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

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

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

  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)
+ [Espace de noms 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)
+ [Espace de noms 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)
+ Espace de noms [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)
+ Espace de noms [Amazon. KeyManagementService.Modèle](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)

### Le code
<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);
    }
  }

}
```

## Considérations supplémentaires
<a name="kms-s3-additional"></a>
+ Vous pouvez vérifier les résultats de cet exemple. Pour ce faire, accédez à la [console Amazon S3](https://console.aws.amazon.com/s3) et ouvrez le compartiment que vous avez fourni à l'application. Recherchez ensuite le nouvel objet, téléchargez-le et ouvrez-le dans un éditeur de texte.
+ La classe [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) implémente la même interface que la classe standard`AmazonS3Client`. Cela facilite le portage de votre code vers la `AmazonS3EncryptionClientV2` classe afin que le chiffrement et le déchiffrement se fassent automatiquement et de manière transparente dans le client.
+ L'un des avantages de l'utilisation d'une AWS KMS clé comme clé principale est que vous n'avez pas besoin de stocker et de gérer vos propres clés principales ; cela se fait par AWS. Un deuxième avantage est que la `AmazonS3EncryptionClientV2` classe du AWS SDK pour .NET est interopérable avec la `AmazonS3EncryptionClientV2` classe du AWS SDK pour Java. Cela signifie que vous pouvez chiffrer avec le AWS SDK pour Java et déchiffrer avec le AWS SDK pour .NET, et vice versa.
**Note**  
La `AmazonS3EncryptionClientV2` classe des AWS SDK pour .NET prend en charge les clés principales KMS uniquement lorsqu'elle est exécutée en mode métadonnées. Le mode de fichier d'instructions de la `AmazonS3EncryptionClientV2` classe du AWS SDK pour .NET est incompatible avec la `AmazonS3EncryptionClientV2` classe du AWS SDK pour Java.
+ Pour plus d'informations sur le chiffrement côté client avec cette `AmazonS3EncryptionClientV2` classe et sur le fonctionnement du chiffrement d'enveloppe, consultez la section [Chiffrement des données côté client avec Amazon AWS SDK pour .NET S3](https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/).