

 AWS SDK untuk .NET V3 telah memasuki mode pemeliharaan.

Kami menyarankan Anda bermigrasi ke [AWS SDK untuk .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html). Untuk detail dan informasi tambahan tentang cara bermigrasi, silakan lihat [pengumuman mode pemeliharaan](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/) kami.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Menggunakan penyimpanan Internet Amazon Simple Storage Service
<a name="s3-apis-intro"></a>

 AWS SDK untuk .NET Mendukung [Amazon S3](https://aws.amazon.com/s3/), yang merupakan penyimpanan untuk Internet. Ini dirancang untuk membuat komputasi skala web lebih mudah bagi pengembang.

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

 AWS SDK untuk .NET Menyediakan APIs untuk klien Amazon S3. Ini APIs memungkinkan Anda untuk bekerja dengan sumber daya Amazon S3 seperti ember dan item. Untuk melihat set lengkap APIs untuk Amazon S3, lihat yang berikut ini:
+ [AWS SDK untuk .NET Referensi API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (dan gulir ke “Amazon.S3").
+ [Dokumentasi Amazon.Extensions.S3.Encryption](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.html)

Amazon S3 APIs disediakan oleh paket-paket berikut: NuGet 
+ [AWSSDK.S3](https://www.nuget.org/packages/AWSSDK.S3)
+ [Amazon.Extensions.S3.Encryption](https://www.nuget.org/packages/Amazon.Extensions.S3.Encryption)

## Prasyarat
<a name="w2aac19c15c21b7"></a>

Sebelum Anda mulai, pastikan Anda telah [mengatur lingkungan dan proyek Anda](net-dg-config.md). Juga tinjau informasi di[Fitur SDK](net-dg-sdk-features.md).

## Contoh dalam dokumen ini
<a name="s3-apis-examples"></a>

Topik berikut dalam dokumen ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk bekerja dengan Amazon S3.
+ [Menggunakan kunci KMS untuk enkripsi S3](kms-keys-s3-encryption.md)

## Contoh dalam dokumen lain
<a name="s3-apis-examples-other"></a>

Tautan berikut ke [Panduan Pengembang Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/) memberikan contoh tambahan tentang cara menggunakan AWS SDK untuk .NET untuk bekerja dengan Amazon S3.

**catatan**  
Meskipun contoh-contoh ini dan pertimbangan pemrograman tambahan dibuat untuk Versi 3 dari AWS SDK untuk .NET menggunakan .NET Framework, mereka juga layak untuk versi yang lebih baru dari AWS SDK untuk .NET menggunakan .NET Core. Penyesuaian kecil dalam kode terkadang diperlukan.

**Contoh pemrograman Amazon S3**
+  [Mengelola ACLs](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-dot-net-sdk.html) 
+  [Membuat Bucket](https://docs.aws.amazon.com/AmazonS3/latest/dev/create-bucket-get-location-example.html#create-bucket-get-location-dotnet) 
+  [Unggah Objek](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)) 
+  [Unggah Multipart dengan API Tingkat Rendah](https://docs.aws.amazon.com/AmazonS3/latest/dev/usingLLmpuDotNet.html) 
+  [Daftar Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/list-obj-version-enabled-bucket.html#list-obj-version-enabled-bucket-sdk-examples) 
+  [Listing Keys](https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingNetSDK.html) 
+  [Dapatkan Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingNetSDK.html) 
+  [Salin Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingNetSDK.html) 
+  [Salin Objek dengan Multipart Upload API](https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingLLNetMPUapi.html) 
+  [Menghapus Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingOneObjectUsingNetSDK.html) 
+  [Menghapus Beberapa Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/DeletingMultipleObjectsUsingNetSDK.html) 
+  [Mengembalikan Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/restore-object-dotnet.html) 
+  [Konfigurasikan Bucket untuk Pemberitahuan](https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html) 
+  [Mengelola Siklus Hidup Objek](https://docs.aws.amazon.com/AmazonS3/latest/dev/manage-lifecycle-using-dot-net.html) 
+  [Menghasilkan URL Objek Pra-ditandatangani](https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLDotNetSDK.html) 
+  [Mengelola Situs Web](https://docs.aws.amazon.com/AmazonS3/latest/dev/ConfigWebSiteDotNet.html) 
+  [Mengaktifkan Berbagi Sumber Daya Lintas Asal (CORS)](https://docs.aws.amazon.com/AmazonS3/latest/dev/ManageCorsUsingDotNet.html) 

**Pertimbangan pemrograman tambahan**
+  [Menggunakan AWS SDK untuk .NET untuk Pemrograman Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingTheMPDotNetAPI.html) 
+  [Membuat Permintaan Menggunakan Kredensil Sementara Pengguna IAM](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempSessionTokenDotNet.html) 
+  [Membuat Permintaan Menggunakan Kredensial Sementara Pengguna Federasi](https://docs.aws.amazon.com/AmazonS3/latest/dev/AuthUsingTempFederationTokenDotNet.html) 
+  [Menentukan Enkripsi Sisi Server](https://docs.aws.amazon.com/AmazonS3/latest/dev/SSEUsingDotNetSDK.html) 
+  [Menentukan Enkripsi Sisi Server dengan Kunci Enkripsi yang Disediakan Pelanggan](https://docs.aws.amazon.com/AmazonS3/latest/dev/sse-c-using-dot-net-sdk.html) 

# Menggunakan AWS KMS kunci untuk enkripsi Amazon S3 di AWS SDK untuk .NET
<a name="kms-keys-s3-encryption"></a>

Contoh ini menunjukkan cara menggunakan AWS Key Management Service kunci untuk mengenkripsi objek Amazon S3. Aplikasi ini membuat kunci master pelanggan (CMK) dan menggunakannya untuk membuat objek [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) untuk enkripsi sisi klien. Aplikasi menggunakan klien tersebut untuk membuat objek terenkripsi dari file teks tertentu di bucket Amazon S3 yang ada. Kemudian mendekripsi objek dan menampilkan isinya.

**Awas**  
Kelas serupa yang `AmazonS3EncryptionClient` disebut tidak digunakan lagi dan kurang aman daripada kelas. `AmazonS3EncryptionClientV2` Untuk memigrasikan kode yang ada yang menggunakan`AmazonS3EncryptionClient`, lihat[Migrasi Klien Enkripsi S3 (V1 ke V2)](s3-encryption-migration-v1-v2.md).

**Topics**
+ [Buat bahan enkripsi](#kms-s3-enc-mat)
+ [Membuat dan mengenkripsi objek Amazon S3](#kms-s3-create-ojbect)
+ [Kode lengkap](#kms-s3-complete-code)
+ [Pertimbangan tambahan](#kms-s3-additional)

## Buat bahan enkripsi
<a name="kms-s3-enc-mat"></a>

Cuplikan berikut membuat `EncryptionMaterials` objek yang berisi ID kunci KMS.

Contoh [di akhir topik ini](#kms-s3-complete-code) menunjukkan cuplikan ini digunakan.

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

## Membuat dan mengenkripsi objek Amazon S3
<a name="kms-s3-create-ojbect"></a>

Cuplikan berikut membuat `AmazonS3EncryptionClientV2` objek yang menggunakan bahan enkripsi yang dibuat sebelumnya. Kemudian menggunakan klien untuk membuat dan mengenkripsi objek Amazon S3 baru.

Contoh [di akhir topik ini](#kms-s3-complete-code) menunjukkan cuplikan ini digunakan.

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

## Kode lengkap
<a name="kms-s3-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c21c13c15b5b1"></a>

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

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

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

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

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

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

  Kelas [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/v3/apidocs/items/S3/NS3Model.html)

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

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

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

  Kelas [AmazonKeyManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/TKeyManagementServiceClient.html)
+ [Namespace Amazon. KeyManagementService.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/KeyManagementService/NKeyManagementServiceModel.html)

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

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

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

}
```

## Pertimbangan tambahan
<a name="kms-s3-additional"></a>
+ Anda dapat memeriksa hasil dari contoh ini. Untuk melakukannya, buka [konsol Amazon S3](https://console.aws.amazon.com/s3) dan buka ember yang Anda berikan ke aplikasi. Kemudian temukan objek baru, unduh, dan buka di editor teks.
+ Kelas [AmazonS3 EncryptionClient V2](https://aws.github.io/amazon-s3-encryption-client-dotnet/api/Amazon.Extensions.S3.Encryption.AmazonS3EncryptionClientV2.html) mengimplementasikan antarmuka yang sama dengan kelas standar. `AmazonS3Client` Ini membuatnya lebih mudah untuk mem-port kode Anda ke `AmazonS3EncryptionClientV2` kelas sehingga enkripsi dan dekripsi terjadi secara otomatis dan transparan di klien.
+ Salah satu keuntungan menggunakan AWS KMS kunci sebagai kunci utama Anda adalah Anda tidak perlu menyimpan dan mengelola kunci master Anda sendiri; ini dilakukan oleh AWS. Keuntungan kedua adalah bahwa `AmazonS3EncryptionClientV2` kelas interoperable dengan `AmazonS3EncryptionClientV2` kelas. AWS SDK untuk .NET AWS SDK untuk Java Ini berarti Anda dapat mengenkripsi dengan AWS SDK untuk Java dan mendekripsi dengan AWS SDK untuk .NET, dan sebaliknya.
**catatan**  
`AmazonS3EncryptionClientV2`Kelas AWS SDK untuk .NET mendukung kunci master KMS hanya ketika dijalankan dalam mode metadata. Mode file instruksi dari `AmazonS3EncryptionClientV2` kelas tidak AWS SDK untuk .NET kompatibel dengan `AmazonS3EncryptionClientV2` kelas file. AWS SDK untuk Java
+ Untuk informasi selengkapnya tentang enkripsi sisi klien dengan `AmazonS3EncryptionClientV2` kelas, dan cara kerja enkripsi amplop, lihat [Enkripsi Data Sisi Klien dengan dan Amazon AWS SDK untuk .NET S3](https://aws.amazon.com/blogs/developer/client-side-data-encryption-with-aws-sdk-for-net-and-amazon-s3/).