

Versi 4 (V4) dari AWS SDK for .NET telah dirilis\$1

Untuk informasi tentang melanggar perubahan dan memigrasi aplikasi Anda, lihat [topik migrasi](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)

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

# Bekerja dengan pasangan kunci Amazon EC2
Pasangan kunci

Amazon EC2 menggunakan kriptografi kunci publik untuk mengenkripsi dan mendekripsi informasi login. Kriptografi kunci publik menggunakan kunci publik untuk mengenkripsi data, dan kemudian penerima menggunakan kunci pribadi untuk mendekripsi data. Kunci publik dan privat dikenal sebagai pasangan kunci. Jika Anda ingin masuk ke instans EC2, Anda harus menentukan key pair ketika Anda meluncurkannya, dan kemudian memberikan kunci pribadi pasangan saat Anda terhubung dengannya.

Saat meluncurkan instans EC2, Anda dapat membuat key pair untuknya atau menggunakan salah satu yang sudah Anda gunakan saat meluncurkan instance lain. Untuk membaca selengkapnya tentang pasangan kunci Amazon EC2, lihat [Bekerja dengan pasangan kunci Amazon EC2 di Panduan](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) Pengguna Amazon [EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/).

Untuk informasi tentang APIs dan prasyarat, lihat bagian induk (). [Bekerja dengan Amazon EC2](ec2-apis-intro.md)

**Topics**
+ [

# Membuat dan menampilkan pasangan kunci
](create-save-key-pair.md)
+ [

# Menghapus pasangan kunci
](delete-key-pairs.md)

# Membuat dan menampilkan pasangan kunci
Membuat pasangan kunci

Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK for .NET to create a key pair. Aplikasi ini mengambil nama untuk key pair baru dan nama file PEM (dengan ekstensi “.pem”). Ini menciptakan keypair, menulis kunci pribadi ke file PEM, dan kemudian menampilkan semua pasangan kunci yang tersedia. Jika Anda tidak memberikan argumen baris perintah, aplikasi hanya menampilkan semua pasangan kunci yang tersedia.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#create-save-key-pair-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [

## Buat pasangan kunci
](#create-save-key-pair-create)
+ [

## Tampilkan pasangan kunci yang tersedia
](#create-save-key-pair-display)
+ [

## Kode lengkap
](#create-save-key-pair-complete-code)
+ [

## Pertimbangan tambahan
](#create-save-key-pair-additional)

## Buat pasangan kunci


Cuplikan berikut membuat key pair dan kemudian menyimpan kunci pribadi ke file PEM yang diberikan.

Contoh [di akhir topik ini](#create-save-key-pair-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to create a key pair and save the key material in a PEM file
    private static async Task CreateKeyPair(
      IAmazonEC2 ec2Client, string keyPairName, string pemFileName)
    {
      // Create the key pair
      CreateKeyPairResponse response =
        await ec2Client.CreateKeyPairAsync(new CreateKeyPairRequest{
          KeyName = keyPairName
        });
      Console.WriteLine($"\nCreated new key pair: {response.KeyPair.KeyName}");

      // Save the private key in a PEM file
      using (var s = new FileStream(pemFileName, FileMode.Create))
      using (var writer = new StreamWriter(s))
      {
        writer.WriteLine(response.KeyPair.KeyMaterial);
      }
    }
```

## Tampilkan pasangan kunci yang tersedia


Cuplikan berikut menampilkan daftar pasangan kunci yang tersedia.

Contoh [di akhir topik ini](#create-save-key-pair-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
```

## Kode lengkap


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

### Referensi SDK


NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  Kelas [CreateKeyPairRequest](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TCreateKeyPairRequest.html)

  Kelas [CreateKeyPairResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TCreateKeyPairResponse.html)

  Kelas [DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeKeyPairsResponse.html)

  Kelas [KeyPairInfo](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TKeyPairInfo.html)

### Kodenya


```
using System;
using System.Threading.Tasks;
using System.IO;
using Amazon.EC2;
using Amazon.EC2.Model;
using System.Collections.Generic;

namespace EC2CreateKeyPair
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create and store a key pair
  class Program
  {
    static async Task Main(string[] args)
    {
      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count == 0)
      {
        // In the case of no command-line arguments,
        // just show help and the existing key pairs
        PrintHelp();
        Console.WriteLine("\nNo arguments specified.");
        Console.Write(
          "Do you want to see a list of the existing key pairs? ((y) or n): ");
        string response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await EnumerateKeyPairs(ec2Client);
        return;
      }

      // Get the application arguments from the parsed list
      string keyPairName =
        CommandLine.GetArgument(parsedArgs, null, "-k", "--keypair-name");
      string pemFileName =
        CommandLine.GetArgument(parsedArgs, null, "-p", "--pem-filename");
      if(string.IsNullOrEmpty(keyPairName))
        CommandLine.ErrorExit("\nNo key pair name specified." +
          "\nRun the command with no arguments to see help.");
      if(string.IsNullOrEmpty(pemFileName) || !pemFileName.EndsWith(".pem"))
        CommandLine.ErrorExit("\nThe PEM filename is missing or incorrect." +
          "\nRun the command with no arguments to see help.");

      // Create the key pair
      await CreateKeyPair(ec2Client, keyPairName, pemFileName);
      await EnumerateKeyPairs(ec2Client);
    }


    //
    // Method to create a key pair and save the key material in a PEM file
    private static async Task CreateKeyPair(
      IAmazonEC2 ec2Client, string keyPairName, string pemFileName)
    {
      // Create the key pair
      CreateKeyPairResponse response =
        await ec2Client.CreateKeyPairAsync(new CreateKeyPairRequest{
          KeyName = keyPairName
        });
      Console.WriteLine($"\nCreated new key pair: {response.KeyPair.KeyName}");

      // Save the private key in a PEM file
      using (var s = new FileStream(pemFileName, FileMode.Create))
      using (var writer = new StreamWriter(s))
      {
        writer.WriteLine(response.KeyPair.KeyMaterial);
      }
    }


    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
        "\nUsage: EC2CreateKeyPair -k <keypair-name> -p <pem-filename>" +
        "\n  -k, --keypair-name: The name you want to assign to the key pair." +
        "\n  -p, --pem-filename: The name of the PEM file to create, with a \".pem\" extension.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // 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

+ Setelah Anda menjalankan contoh, Anda dapat melihat key pair baru di konsol [Amazon EC2](https://console.aws.amazon.com/ec2/#KeyPairs).
+ Ketika Anda membuat key pair, Anda harus menyimpan kunci pribadi yang dikembalikan karena Anda tidak dapat mengambil kunci pribadi nanti.

# Menghapus pasangan kunci


Contoh ini menunjukkan kepada Anda cara menggunakan AWS SDK for .NET to delete a key pair. Aplikasi ini mengambil nama sebuah key pair. Ini menghapus key pair dan kemudian menampilkan semua pasangan kunci yang tersedia. Jika Anda tidak memberikan argumen baris perintah, aplikasi hanya menampilkan semua pasangan kunci yang tersedia.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#delete-key-pairs-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [

## Hapus key pair
](#delete-key-pairs-create)
+ [

## Tampilkan pasangan kunci yang tersedia
](#delete-key-pairs-display)
+ [

## Kode lengkap
](#delete-key-pairs-complete-code)

## Hapus key pair


Cuplikan berikut menghapus key pair.

Contoh [di akhir topik ini](#delete-key-pairs-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to delete a key pair
    private static async Task DeleteKeyPair(IAmazonEC2 ec2Client, string keyName)
    {
      await ec2Client.DeleteKeyPairAsync(new DeleteKeyPairRequest{
        KeyName = keyName});
      Console.WriteLine($"\nKey pair {keyName} has been deleted (if it existed).");
    }
```

## Tampilkan pasangan kunci yang tersedia


Cuplikan berikut menampilkan daftar pasangan kunci yang tersedia.

Contoh [di akhir topik ini](#delete-key-pairs-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
```

## Kode lengkap


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

### Referensi SDK


NuGet paket:
+ [AWSSDK.EC2](https://www.nuget.org/packages/AWSSDK.EC2)

Elemen pemrograman:
+ [Namespace Amazon.EC2](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2.html)

  [EC2Klien Kelas Amazon](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TEC2Client.html)
+ [Namespace Amazon.EC2.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/NEC2Model.html)

  Kelas [https://docs.aws.amazon.com/sdkfornet/v4/apidocs/](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/)

  Kelas [DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TDescribeKeyPairsResponse.html)

  Kelas [KeyPairInfo](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/EC2/TKeyPairInfo.html)

### Kodenya


```
using System;
using System.Threading.Tasks;
using Amazon.EC2;
using Amazon.EC2.Model;

namespace EC2DeleteKeyPair
{
  class Program
  {
    static async Task Main(string[] args)
    {
      // Create the EC2 client
      var ec2Client = new AmazonEC2Client();

      if(args.Length == 1)
      {
        // Delete a key pair (if it exists)
        await DeleteKeyPair(ec2Client, args[0]);

        // Display the key pairs that are left
        await EnumerateKeyPairs(ec2Client);
      }
      else
      {
        Console.WriteLine("\nUsage: EC2DeleteKeyPair keypair-name");
        Console.WriteLine("  keypair-name - The name of the key pair you want to delete.");
        Console.WriteLine("\nNo arguments specified.");
        Console.Write(
          "Do you want to see a list of the existing key pairs? ((y) or n): ");
        string response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await EnumerateKeyPairs(ec2Client);
      }
    }


    //
    // Method to delete a key pair
    private static async Task DeleteKeyPair(IAmazonEC2 ec2Client, string keyName)
    {
      await ec2Client.DeleteKeyPairAsync(new DeleteKeyPairRequest{
        KeyName = keyName});
      Console.WriteLine($"\nKey pair {keyName} has been deleted (if it existed).");
    }


    //
    // Method to show the key pairs that are available
    private static async Task EnumerateKeyPairs(IAmazonEC2 ec2Client)
    {
      DescribeKeyPairsResponse response = await ec2Client.DescribeKeyPairsAsync();
      Console.WriteLine("Available key pairs:");
      foreach (KeyPairInfo item in response.KeyPairs)
        Console.WriteLine($"  {item.KeyName}");
    }
  }
}
```