

Version 4 (V4) von AWS SDK für .NET wurde veröffentlicht\$1

Informationen zu wichtigen Änderungen und zur Migration Ihrer Anwendungen finden Sie im [Migrationsthema](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)

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Verwendung von AWS KMS Schlüsseln für die Amazon S3 S3-Verschlüsselung in AWS SDK für .NET
<a name="kms-keys-s3-encryption"></a>

Dieses Beispiel zeigt Ihnen, wie Sie AWS Key Management Service Schlüssel verwenden, um Amazon S3 S3-Objekte zu verschlüsseln. Die Anwendung erstellt einen Kundenhauptschlüssel (CMK) und verwendet ihn, um ein [AmazonS3 EncryptionClient V2-Objekt für die clientseitige Verschlüsselung](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) zu erstellen. Die Anwendung verwendet diesen Client, um ein verschlüsseltes Objekt aus einer bestimmten Textdatei in einem vorhandenen Amazon S3 S3-Bucket zu erstellen. Anschließend entschlüsselt sie das Objekt und zeigt seinen Inhalt an.

**Warnung**  
Eine ähnliche Klasse namens `AmazonS3EncryptionClient` ist veraltet und weniger sicher als die Klasse. `AmazonS3EncryptionClientV2` Informationen zur Migration von vorhandenem Code, der verwendet`AmazonS3EncryptionClient`, finden Sie unter. [Migration des S3-Verschlüsselungsclients (V1 auf V2)](s3-encryption-migration-v1-v2.md)

**Topics**
+ [Verschlüsselungsmaterial erstellen](#kms-s3-enc-mat)
+ [Ein Amazon S3 S3-Objekt erstellen und verschlüsseln](#kms-s3-create-ojbect)
+ [Vollständiger Code](#kms-s3-complete-code)
+ [Weitere Überlegungen](#kms-s3-additional)

## Verschlüsselungsmaterial erstellen
<a name="kms-s3-enc-mat"></a>

Mit dem folgenden Codeausschnitt wird ein `EncryptionMaterials` Objekt erstellt, das eine KMS-Schlüssel-ID enthält.

Das Beispiel [am Ende dieses Themas zeigt, wie dieser](#kms-s3-complete-code) Codeausschnitt verwendet wird.

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

## Ein Amazon S3 S3-Objekt erstellen und verschlüsseln
<a name="kms-s3-create-ojbect"></a>

Der folgende Ausschnitt erstellt ein `AmazonS3EncryptionClientV2` Objekt, das die zuvor erstellten Verschlüsselungsmaterialien verwendet. Anschließend verwendet es den Client, um ein neues Amazon S3 S3-Objekt zu erstellen und zu verschlüsseln.

Das Beispiel [am Ende dieses Themas zeigt, wie dieses](#kms-s3-complete-code) Snippet verwendet wird.

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

## Vollständiger Code
<a name="kms-s3-complete-code"></a>

Dieser Abschnitt enthält relevante Referenzen und den vollständigen Code für dieses Beispiel.

### SDK-Referenzen
<a name="w2aac19c15c25c13c15b5b1"></a>

NuGet Pakete:
+ [Amazon.Extensions.S3. Verschlüsselung](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

Elemente der Programmierung:
+ [Namespace Amazon.Extensions.S3.Verschlüsselung](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

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

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

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

  Klasse [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)

  Klasse [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)

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

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

  Klasse [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)

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

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

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

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

}
```

## Weitere Überlegungen
<a name="kms-s3-additional"></a>
+ Sie können die Ergebnisse dieses Beispiels überprüfen. Rufen Sie dazu die [Amazon S3 S3-Konsole](https://console.aws.amazon.com/s3) auf und öffnen Sie den Bucket, den Sie der Anwendung zur Verfügung gestellt haben. Suchen Sie dann das neue Objekt, laden Sie es herunter und öffnen Sie es in einem Texteditor.
+ Die [AmazonS3 EncryptionClient V2-Klasse](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) implementiert dieselbe Schnittstelle wie die `AmazonS3Client` Standardklasse. Dies erleichtert die Portierung Ihres Codes in die `AmazonS3EncryptionClientV2` Klasse, sodass die Verschlüsselung und Entschlüsselung automatisch und transparent im Client erfolgt.
+ Ein Vorteil der Verwendung eines AWS KMS Schlüssels als Hauptschlüssel besteht darin, dass Sie Ihre eigenen Hauptschlüssel nicht speichern und verwalten müssen. Dies erfolgt durch. AWS Ein zweiter Vorteil besteht darin, dass die `AmazonS3EncryptionClientV2` Klasse von mit der `AmazonS3EncryptionClientV2` Klasse von interoperabel AWS SDK für .NET ist. AWS SDK für Java Das heißt, Sie können mit dem verschlüsseln AWS SDK für Java und mit dem entschlüsseln und AWS SDK für .NET umgekehrt.
**Anmerkung**  
Die `AmazonS3EncryptionClientV2` Klasse von AWS SDK für .NET unterstützt KMS-Masterschlüssel nur, wenn sie im Metadatenmodus ausgeführt wird. Der Befehlsdateimodus der `AmazonS3EncryptionClientV2` Klasse von AWS SDK für .NET ist nicht kompatibel mit der `AmazonS3EncryptionClientV2` Klasse von AWS SDK für Java.
+ Weitere Informationen zur clientseitigen Verschlüsselung mit der `AmazonS3EncryptionClientV2` Klasse und zur Funktionsweise der Envelope-Verschlüsselung finden Sie unter [Clientseitige Datenverschlüsselung mit AWS SDK für .NET und Amazon S3](https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/).