

 适用于 .NET 的 AWS SDK V3 已进入维护模式。

我们建议您迁移到 [适用于 .NET 的 AWS SDK V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html)。有关如何迁移的更多详细信息和信息，请参阅我们的[维护模式公告](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 Amazon Simple Storage Service Internet 存储
<a name="s3-apis-intro"></a>

 适用于 .NET 的 AWS SDK 支持用于互联网存储的 [Amazon S3](https://aws.amazon.com/s3/)。该服务旨在降低开发人员进行网络规模级计算的难度。

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

针 适用于 .NET 的 AWS SDK 对 Amazon S3 客户端。 APIs APIs 使您能够使用 Amazon S3 资源，例如存储桶和项目。要查看 Amazon S3 APIs 的完整套件，请参阅以下内容：
+ [适用于 .NET 的 AWS SDK API 参考](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/)（然后滚动至 “Amazon.S3”）。
+ [Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html) 文档

Amazon S3 APIs 由以下 NuGet 软件包提供：
+ [AWSSDK.S3](https://www.nuget.org/packages/AWSSDK.S3)
+ [Amazon.Extensions.S3.Encryption](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

## 先决条件
<a name="w2aac19c15c21b7"></a>

开始之前，请确保您已[完成环境和项目的设置](net-dg-config.md)。还要查看[软件开发工具包功能](net-dg-sdk-features.md)中的信息。

## 本文档中的示例
<a name="s3-apis-examples"></a>

本文档中的以下主题向您展示了如何使用与 Amazon S3 配合使用。 适用于 .NET 的 AWS SDK 
+ [使用 KMS 密钥进行 S3 加密](kms-keys-s3-encryption.md)

## 其它文档中的示例
<a name="s3-apis-examples-other"></a>

以下指[向 Amazon S3 开发者指南](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)的链接提供了更多示例，说明如何使用与 Amazon S3 配合使用。 适用于 .NET 的 AWS SDK 

**注意**  
尽管这些示例和其他编程注意事项是为 适用于 .NET 的 AWS SDK 使用.NET Framework 的版本 3 创建的，但它们也适用于 适用于 .NET 的 AWS SDK 使用.NET Core 的更高版本。有时需要对代码进行细微调整。

**Amazon S3 编程示例**
+  [管理 ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-dot-net-sdk.html) 
+  [创建存储桶](https://docs.aws.amazon.com/AmazonS3/latest/dev/create-bucket-get-location-example.html#create-bucket-get-location-dotnet) 
+  [上传对象](https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpNET.html) 
+  使用@@ [高级别 API ([Amazon.S3.Transfer) 进行分段上传。 TransferUtility](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TTransferUtility.html)](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingHLmpuDotNet.html)) 
+  [使用低级别 API 的分段上传](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingLLmpuDotNet.html) 
+  [列出对象](https://docs.aws.amazon.com/AmazonS3/latest/dev/list-obj-version-enabled-bucket.html#list-obj-version-enabled-bucket-sdk-examples) 
+  [列出密钥](https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingNetSDK.html) 
+  [获取对象](https://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingNetSDK.html) 
+  [复制对象](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingNetSDK.html) 
+  [使用分段上传 API 复制对象](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingLLNetMPUapi.html) 
+  [删除对象](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingOneObjectUsingNetSDK.html) 
+  [删除多个对象](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingNetSDK.html) 
+  [恢复对象](https://docs.aws.amazon.com/AmazonS3/latest/dev/restore-object-dotnet.html) 
+  [为通知配置存储桶](https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html) 
+  [管理对象的生命周期](https://docs.aws.amazon.com/AmazonS3/latest/dev/manage-lifecycle-using-dot-net.html) 
+  [生成预签名对象 URL](https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLDotNetSDK.html) 
+  [管理网站](https://docs.aws.amazon.com/AmazonS3/latest/dev/ConfigWebSiteDotNet.html) 
+  [允许跨源资源共享 (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/ManageCorsUsingDotNet.html) 

**其它编程注意事项**
+  [使用 适用于 .NET 的 AWS SDK 进行 Amazon S3 编程](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingTheMPDotNetAPI.html) 
+  [使用 IAM 用户临时证书创建请求](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempSessionTokenDotNet.html) 
+  [使用联合身份用户临时凭证创建请求](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempFederationTokenDotNet.html) 
+  [指定服务器端加密](https://docs.aws.amazon.com/AmazonS3/latest/dev/SSEUsingDotNetSDK.html) 
+  [使用客户提供的加密密钥指定服务器端加密](https://docs.aws.amazon.com/AmazonS3/latest/dev/sse-c-using-dot-net-sdk.html) 

# 在中使用 AWS KMS 密钥进行 Amazon S3 加密 适用于 .NET 的 AWS SDK
<a name="kms-keys-s3-encryption"></a>

此示例向您展示如何使用 AWS Key Management Service 密钥加密 Amazon S3 对象。该应用程序创建客户主密钥 (CMK)，并使用它来创建用于客户端加密的 A [mazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) 对象。应用程序使用该客户端根据现有 Amazon S3 桶中的给定文本文件创建加密对象。然后，它会解密对象并显示其内容。

**警告**  
名为`AmazonS3EncryptionClient`的类似类已被弃用，其安全性不如 `AmazonS3EncryptionClientV2` 类。要迁移使用 `AmazonS3EncryptionClient` 的现有代码，请参阅[S3 加密客户端迁移（从 V1 到 V2）](s3-encryption-migration-v1-v2.md)。

**Topics**
+ [创建加密材料](#kms-s3-enc-mat)
+ [创建并加密 Amazon S3 对象](#kms-s3-create-ojbect)
+ [完整代码](#kms-s3-complete-code)
+ [其他注意事项](#kms-s3-additional)

## 创建加密材料
<a name="kms-s3-enc-mat"></a>

以下代码片段创建了一个包含 KMS 密钥 ID 的 `EncryptionMaterials` 对象。

[本主题末尾](#kms-s3-complete-code)的示例显示了此片段的使用情况。

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

## 创建并加密 Amazon S3 对象
<a name="kms-s3-create-ojbect"></a>

以下代码片段创建了一个使用先前创建的加密材料的 `AmazonS3EncryptionClientV2` 对象。然后，它使用客户端来创建和加密一个新的 Amazon S3 对象。

[本主题末尾](#kms-s3-complete-code)的示例显示了此片段的使用情况。

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

## 完整代码
<a name="kms-s3-complete-code"></a>

本部分显示了本示例的相关参考和完整代码。

### SDK 参考
<a name="w2aac19c15c21c13c15b5b1"></a>

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

编程元素：
+ 命名空间 [Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

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

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

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

  [EncryptionMaterialsV](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.EncryptionMaterialsV2.html) 2 级
+ 命名空间 [Amazon.Extensions.S3.Encryption.Primitives](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.Primitives.html)

  班级 [KmsType](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.Primitives.KmsType.html)
+ 命名空间 [Amazon.S3.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/NS3Model.html)

  班级 [GetObjectRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TGetObjectRequest.html)

  班级 [GetObjectResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TGetObjectResponse.html)

  班级 [PutObjectRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/S3/TPutObjectRequest.html)
+ 命名空间 [Amazon。 KeyManagementService](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/NKeyManagementService.html)

  班级 [AmazonKeyManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TKeyManagementServiceClient.html)
+ 命名空间 [Amazon。 KeyManagementService.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/NKeyManagementServiceModel.html)

  班级 [CreateKeyRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TCreateKeyRequest.html)

  班级 [CreateKeyResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TCreateKeyResponse.html)

### 代码
<a name="w2aac19c15c21c13c15b7b1"></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);
    }
  }

}
```

## 其他注意事项
<a name="kms-s3-additional"></a>
+ 您可以查看此示例的结果。为此，请前往 [Amazon S3 控制台](https://console.aws.amazon.com/s3)并打开您提供给应用程序的桶。然后找到新对象，下载后在文本编辑器中打开该对象。
+ A [mazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) 类实现的接口与标准`AmazonS3Client`类相同。这样可以更轻松地将代码移植到 `AmazonS3EncryptionClientV2` 类中，从而在客户端中自动透明地进行加密和解密。
+ 使用 AWS KMS 密钥作为主密钥的一个好处是，您无需存储和管理自己的主密钥；这是通过完成的 AWS。第二个优点是，的`AmazonS3EncryptionClientV2` 适用于 .NET 的 AWS SDK 类可以与的`AmazonS3EncryptionClientV2`类互操作。 适用于 Java 的 AWS SDK这意味着您可以使用加密 适用于 Java 的 AWS SDK 并使用解密 适用于 .NET 的 AWS SDK，反之亦然。
**注意**  
的`AmazonS3EncryptionClientV2`类仅在元数据模式下运行时 适用于 .NET 的 AWS SDK 支持 KMS 主密钥。的`AmazonS3EncryptionClientV2`类的指令文件模式与的`AmazonS3EncryptionClientV2`类 适用于 .NET 的 AWS SDK 不兼容 适用于 Java 的 AWS SDK。
+ 有关该`AmazonS3EncryptionClientV2`类的客户端加密以及信封加密的工作原理的更多信息，请参阅使用[适用于 .NET 的 AWS SDK 和 Amazon S3 进行客户端数据加密](https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/)。