

 AWS SDK for .NET V3 がメンテナンスモードになりました。

[AWS SDK for .NET 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 インターネットストレージの使用
<a name="s3-apis-intro"></a>

は、インターネット用のストレージである [Amazon S3](https://aws.amazon.com/s3/) AWS SDK for .NET をサポートしています。Web スケールのコンピューティングを開発者が容易にできるように設計されています。

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

 AWS SDK for .NET はAPIs Amazon S3を提供します。API を使用すると、バケットやアイテムなどの Amazon S3 リソースを操作できます。Amazon S3 向け API の完全なセットを表示するには、以下を参照してください。
+ [AWS SDK for .NET 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 API は、以下の 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)ことを必ず確認してください。また、「[SDK の機能](net-dg-sdk-features.md)」の情報を確認してください。

## このドキュメントで取り上げる例
<a name="s3-apis-examples"></a>

このドキュメントの以下のトピックでは、 AWS SDK for .NET を使用して Amazon S3 を操作する方法について説明します。
+ [S3 暗号化用 KMS キーの使用](kms-keys-s3-encryption.md)

## 他のドキュメントで取り上げられている例
<a name="s3-apis-examples-other"></a>

以下の [Amazon S3 デベロッパーガイドへのリンク](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)は、 を使用して Amazon S3 AWS SDK for .NET を操作する方法の追加の例を示しています。

**注記**  
これらの例と追加のプログラミング上の考慮事項は、.NET Framework AWS SDK for .NET を使用する のバージョン 3 用に作成されていますが、.NET Core AWS SDK for .NET を使用する のそれ以降のバージョンでも実行可能です。コードの軽微な修正が必要になる場合があります。

**Amazon S3 プログラミングの例**
+  [ACL の管理](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) 
+  [Cross-Origin Resource Sharing (CORS) の有効化](https://docs.aws.amazon.com/AmazonS3/latest/dev/ManageCorsUsingDotNet.html) 

**プログラミングに関するその他の考慮事項**
+  [Amazon S3 プログラミングでの AWS SDK for .NET の使用](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) 

# での Amazon S3 暗号化の AWS KMS キーの使用 AWS SDK for .NET
<a name="kms-keys-s3-encryption"></a>

この例では、 AWS Key Management Service キーを使用して Amazon S3 オブジェクトを暗号化する方法を示します。アプリケーションはカスタマーマスターキー (CMK) を作成し、これを使用してクライアント側の暗号化に使用する [AmazonS3EncryptionClientV2](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)

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

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

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

  クラス [EncryptionMaterialsV2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.EncryptionMaterialsV2.html)
+ 名前空間 [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)に移動し、アプリケーションに対して指定したバケットを開きます。次に、新しいオブジェクトを見つけてダウンロードし、テキストエディタで開きます。
+ [AmazonS3EncryptionClientV2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) クラスでは、標準の `AmazonS3Client` クラスと同じインターフェイスが実装されています。そのため、暗号化と復号化がクライアント側で自動的かつ透過的に行われるよう、コードを `AmazonS3EncryptionClientV2` クラスに移植するのが容易になります。
+ キーをマスター AWS KMS キーとして使用する利点の 1 つは、独自のマスターキーを保存および管理する必要がないことです。これは によって行われます AWS。もう 1 つの利点は、 の `AmazonS3EncryptionClientV2` クラス AWS SDK for .NET が の `AmazonS3EncryptionClientV2` クラスと相互運用できることです AWS SDK for Java。つまり、 で暗号化 AWS SDK for Java し AWS SDK for .NET、 で復号できます。逆も同様です。
**注記**  
の `AmazonS3EncryptionClientV2` クラスは、メタデータモードで実行されている場合にのみ KMS マスターキー AWS SDK for .NET をサポートします。の `AmazonS3EncryptionClientV2`クラスの命令ファイルモード AWS SDK for .NET は、 の `AmazonS3EncryptionClientV2`クラスの と互換性がありません AWS SDK for Java。
+ `AmazonS3EncryptionClientV2` クラスによるクライアント側の暗号化、およびエンベロープ暗号化の仕組みの詳細については、「 [AWS SDK for .NET および Amazon S3 によるクライアント側のデータ暗号化](https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/)」を参照してください。