View a markdown version of this page

Gunakan CreateKey dengan AWS SDK atau CLI - AWS Key Management Service

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

Gunakan CreateKey dengan AWS SDK atau CLI

Contoh-contoh kode berikut menunjukkan cara menggunakan CreateKey.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
SDK untuk .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode AWS.

using System; using System.Threading.Tasks; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; /// <summary> /// Shows how to create a new AWS Key Management Service (AWS KMS) /// key. /// </summary> public class CreateKey { public static async Task Main() { // Note that if you need to create a Key in an AWS Region // other than the Region defined for the default user, you need to // pass the Region to the client constructor. var client = new AmazonKeyManagementServiceClient(); // The call to CreateKeyAsync will create a symmetrical AWS KMS // key. For more information about symmetrical and asymmetrical // keys, see: // // https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-choose.html var response = await client.CreateKeyAsync(new CreateKeyRequest()); // The KeyMetadata object contains information about the new AWS KMS key. KeyMetadata keyMetadata = response.KeyMetadata; if (keyMetadata is not null) { Console.WriteLine($"KMS Key: {keyMetadata.KeyId} was successfully created."); } else { Console.WriteLine("Could not create KMS Key."); } } }
  • Untuk detail API, lihat CreateKey di AWS SDK untuk .NET Referensi API.

CLI
AWS CLI

Contoh 1: Untuk membuat kunci KMS yang dikelola pelanggan di AWS KM

Berikut ini create-key contoh membuat kunci KMS enkripsi simetris.

Untuk membuat kunci KMS dasar, kunci enkripsi simetris, Anda tidak perlu menentukan parameter apa pun. Nilai default untuk parameter tersebut membuat kunci enkripsi simetris.

Karena perintah ini tidak menentukan kebijakan kunci, kunci KMS mendapatkan kebijakan kunci default untuk kunci KMS yang dibuat secara terprogram. Untuk melihat kebijakan utama, gunakan get-key-policy perintah. Untuk mengubah kebijakan kunci, gunakan put-key-policy perintah.

aws kms create-key

create-key perintah mengembalikan metadata kunci, termasuk ID kunci dan ARN dari kunci KMS baru. Anda dapat menggunakan nilai-nilai ini untuk mengidentifikasi kunci KMS di lainnya AWS Operasi KMS. Outputnya tidak termasuk tag. Untuk melihat tag untuk kunci KMS, gunakan list-resource-tags command.

Output:

{ "KeyMetadata": { "AWSAccountId": "123456789012", "Arn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "CreationDate": "2017-07-05T14:04:55-07:00", "CurrentKeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "Description": "", "Enabled": true, "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "AWS_KMS", "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ] } }

Catatan: create-key perintah tidak memungkinkan Anda menentukan alias, Untuk membuat alias untuk kunci KMS baru, gunakan create-alias perintah.

Untuk informasi lebih lanjut, lihat Membuat kunci di AWS Panduan Pengembang Layanan Manajemen Kunci.

Contoh 2: Untuk membuat kunci RSA KMS asimetris untuk enkripsi dan dekripsi

Berikut ini create-key contoh membuat kunci KMS yang berisi pasangan kunci RSA asimetris untuk enkripsi dan dekripsi. Spesifikasi kunci dan penggunaan kunci tidak dapat diubah setelah kunci dibuat.

aws kms create-key \ --key-spec RSA_4096 \ --key-usage ENCRYPT_DECRYPT

Output:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "AWSAccountId": "123456789012", "CreationDate": "2021-04-05T14:04:55-07:00", "CustomerMasterKeySpec": "RSA_4096", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256" ], "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "KeyManager": "CUSTOMER", "KeySpec": "RSA_4096", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "AWS_KMS" } }

Untuk informasi lebih lanjut, lihat Kunci asimetris di AWS KM di AWS Panduan Pengembang Layanan Manajemen Kunci.

Contoh 3: Untuk membuat kunci KMS kurva elips asimetris untuk penandatanganan dan verifikasi

Berikut ini create-key contoh membuat kunci KMS asimetris yang berisi pasangan kunci kurva elips asimetris (ECC) untuk penandatanganan dan verifikasi. --key-usage Parameter diperlukan meskipun SIGN_VERIFY adalah satu-satunya nilai yang valid untuk kunci ECC KMS. Spesifikasi kunci dan penggunaan kunci tidak dapat diubah setelah kunci dibuat.

aws kms create-key \ --key-spec ECC_NIST_P521 \ --key-usage SIGN_VERIFY

Output:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "AWSAccountId": "123456789012", "CreationDate": "2019-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "ECC_NIST_P521", "Description": "", "Enabled": true, "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "KeyManager": "CUSTOMER", "KeySpec": "ECC_NIST_P521", "KeyState": "Enabled", "KeyUsage": "SIGN_VERIFY", "MultiRegion": false, "Origin": "AWS_KMS", "SigningAlgorithms": [ "ECDSA_SHA_512" ] } }

Untuk informasi lebih lanjut, lihat Kunci asimetris di AWS KM di AWS Panduan Pengembang Layanan Manajemen Kunci.

Contoh 4: Untuk membuat asimetris ML-DSA Kunci KMS untuk penandatanganan dan verifikasi

Berikut ini create-key contoh membuat algoritma tanda tangan digital kisi modul (ML-DSA) kunci untuk penandatanganan dan verifikasi. Parameter penggunaan kunci diperlukan meskipun SIGN_VERIFY adalah satu-satunya nilai yang valid untuk ML-DSA kunci.

aws kms create-key \ --key-spec ML_DSA_65 \ --key-usage SIGN_VERIFY

Output:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "AWSAccountId": "123456789012", "CreationDate": "2019-12-02T07:48:55-07:00", "Description": "", "Enabled": true, "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "KeyManager": "CUSTOMER", "KeySpec": "ML_DSA_65", "KeyState": "Enabled", "KeyUsage": "SIGN_VERIFY", "MultiRegion": false, "Origin": "AWS_KMS", "SigningAlgorithms": [ "ML_DSA_SHAKE_256" ] } }

Untuk informasi lebih lanjut, lihat Kunci asimetris di AWS KM di AWS Panduan Pengembang Layanan Manajemen Kunci.

Contoh 5: Untuk membuat kunci HMAC KMS

Berikut ini create-key contoh membuat kunci KMS HMAC 384-bit. GENERATE_VERIFY_MAC nilai untuk --key-usage parameter diperlukan meskipun itu satu-satunya nilai yang valid untuk kunci HMAC KMS.

aws kms create-key \ --key-spec HMAC_384 \ --key-usage GENERATE_VERIFY_MAC

Output:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "AWSAccountId": "123456789012", "CreationDate": "2022-04-05T14:04:55-07:00", "CustomerMasterKeySpec": "HMAC_384", "Description": "", "Enabled": true, "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "KeyManager": "CUSTOMER", "KeySpec": "HMAC_384", "KeyState": "Enabled", "KeyUsage": "GENERATE_VERIFY_MAC", "MacAlgorithms": [ "HMAC_SHA_384" ], "MultiRegion": false, "Origin": "AWS_KMS" } }

Untuk informasi lebih lanjut, lihat Kunci HMAC masuk AWS KM di AWS Panduan Pengembang Layanan Manajemen Kunci.

Contoh 6: Untuk membuat kunci KMS utama Multi-wilayah

Berikut ini create-key contoh membuat kunci enkripsi simetris primer Multi-wilayah. Karena nilai default untuk semua parameter membuat kunci enkripsi simetris, hanya --multi-region parameter diperlukan untuk kunci KMS ini. Di AWS CLI, untuk menunjukkan bahwa parameter Boolean benar, cukup tentukan nama parameter.

aws kms create-key \ --multi-region

Output:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:123456789012:key/mrk-1234abcd12ab34cd56ef12345678990ab", "AWSAccountId": "123456789012", "CreationDate": "2021-09-02T016:15:21-09:00", "CurrentKeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "mrk-1234abcd12ab34cd56ef12345678990ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": true, "MultiRegionConfiguration": { "MultiRegionKeyType": "PRIMARY", "PrimaryKey": { "Arn": "arn:aws:kms:us-west-2:123456789012:key/mrk-1234abcd12ab34cd56ef12345678990ab", "Region": "us-west-2" }, "ReplicaKeys": [] }, "Origin": "AWS_KMS" } }

Untuk informasi lebih lanjut, lihat Kunci asimetris di AWS KM di AWS Panduan Pengembang Layanan Manajemen Kunci.

Contoh 7: Untuk membuat kunci KMS untuk bahan kunci yang diimpor

Berikut ini create-key contoh membuat sebuah membuat kunci KMS tanpa bahan kunci. Ketika operasi selesai, Anda dapat mengimpor materi kunci Anda sendiri ke kunci KMS. Untuk membuat kunci KMS ini, atur --origin parameter untuk EXTERNAL.

aws kms create-key \ --origin EXTERNAL

Output:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "AWSAccountId": "123456789012", "CreationDate": "2019-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "Description": "", "Enabled": false, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "PendingImport", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "EXTERNAL" } }

Untuk informasi lebih lanjut, lihat Mengimpor materi utama di AWS Kunci KMS di AWS Panduan Pengembang Layanan Manajemen Kunci.

Contoh 8: Untuk membuat kunci KMS di AWS Toko kunci CloudHSM

Berikut ini create-key contoh membuat sebuah membuat kunci KMS di yang ditentukan AWS Toko kunci CloudHSM. Operasi membuat kunci KMS dan metadatanya di AWS KMS dan menciptakan materi kunci di AWS Cluster CloudHSM terkait dengan penyimpanan kunci khusus. Parameter --custom-key-store-id dan --origin diperlukan.

aws kms create-key \ --origin AWS_CLOUDHSM \ --custom-key-store-id cks-1234567890abcdef0

Output:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "AWSAccountId": "123456789012", "CloudHsmClusterId": "cluster-1a23b4cdefg", "CreationDate": "2019-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "CustomKeyStoreId": "cks-1234567890abcdef0", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "AWS_CLOUDHSM" } }

Untuk informasi lebih lanjut, lihat AWS Toko kunci CloudHSM di AWS Panduan Pengembang Layanan Manajemen Kunci.

Contoh 9: Untuk membuat kunci KMS di penyimpanan kunci eksternal

Berikut ini create-key contoh membuat sebuah membuat kunci KMS di penyimpanan kunci eksternal yang ditentukan. --custom-key-store-id, --origin, dan --xks-key-id parameter diperlukan dalam perintah ini.

--xks-key-id parameter menentukan ID kunci enkripsi simetris yang ada di pengelola kunci eksternal Anda. Kunci ini berfungsi sebagai bahan kunci eksternal untuk kunci KMS. Nilai --origin Parameter harus EXTERNAL_KEY_STORE./ custom-key-store-id parameter harus mengidentifikasi penyimpanan kunci eksternal yang terhubung ke proxy penyimpanan kunci eksternalnya.

aws kms create-key \ --origin EXTERNAL_KEY_STORE \ --custom-key-store-id cks-9876543210fedcba9 \ --xks-key-id bb8562717f809024

Output:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "AWSAccountId": "123456789012", "CreationDate": "2022-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "CustomKeyStoreId": "cks-9876543210fedcba9", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "EXTERNAL_KEY_STORE", "XksKeyConfiguration": { "Id": "bb8562717f809024" } } }

Untuk informasi lebih lanjut, lihat Toko kunci eksternal di AWS Panduan Pengembang Layanan Manajemen Kunci.

  • Untuk detail API, lihat CreateKey di AWS CLI Referensi Perintah.

Java
SDK untuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode AWS.

/** * Creates a new symmetric encryption key asynchronously. * * @param keyDesc the description of the key to be created * @return a {@link CompletableFuture} that completes with the ID of the newly created key * @throws RuntimeException if an error occurs while creating the key */ public CompletableFuture<String> createKeyAsync(String keyDesc) { CreateKeyRequest keyRequest = CreateKeyRequest.builder() .description(keyDesc) .keySpec(KeySpec.SYMMETRIC_DEFAULT) .keyUsage(KeyUsageType.ENCRYPT_DECRYPT) .build(); return getAsyncClient().createKey(keyRequest) .thenApply(resp -> resp.keyMetadata().keyId()) .exceptionally(ex -> { throw new RuntimeException("An error occurred while creating the key: " + ex.getMessage(), ex); }); }
  • Untuk detail API, lihat CreateKey di AWS SDK for Java 2.x Referensi API.

Kotlin
SDK untuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode AWS.

suspend fun createKey(keyDesc: String?): String? { val request = CreateKeyRequest { description = keyDesc customerMasterKeySpec = CustomerMasterKeySpec.SymmetricDefault keyUsage = KeyUsageType.fromValue("ENCRYPT_DECRYPT") } KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient -> val result = kmsClient.createKey(request) println("Created a customer key with id " + result.keyMetadata?.arn) return result.keyMetadata?.keyId } }
  • Untuk detail API, lihat CreateKey di AWS SDK untuk referensi API Kotlin.

PHP
SDK untuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode AWS.

/*** * @param string $keySpec * @param string $keyUsage * @param string $description * @return array */ public function createKey(string $keySpec = "", string $keyUsage = "", string $description = "Created by the SDK for PHP") { $parameters = ['Description' => $description]; if($keySpec && $keyUsage){ $parameters['KeySpec'] = $keySpec; $parameters['KeyUsage'] = $keyUsage; } try { $result = $this->client->createKey($parameters); return $result['KeyMetadata']; }catch(KmsException $caught){ // Check for error specific to createKey operations if ($caught->getAwsErrorMessage() == "LimitExceededException"){ echo "The request was rejected because a quota was exceeded. For more information, see Quotas in the Key Management Service Developer Guide."; } throw $caught; } }
  • Untuk detail API, lihat CreateKey di AWS SDK untuk PHP Referensi API.

Python
SDK untuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode AWS.

class KeyManager: def __init__(self, kms_client): self.kms_client = kms_client self.created_keys = [] @classmethod def from_client(cls) -> "KeyManager": """ Creates a KeyManager instance with a default KMS client. :return: An instance of KeyManager initialized with the default KMS client. """ kms_client = boto3.client("kms") return cls(kms_client) def create_key(self, key_description: str) -> dict[str, any]: """ Creates a key with a user-provided description. :param key_description: A description for the key. :return: The key ID. """ try: key = self.kms_client.create_key(Description=key_description)["KeyMetadata"] self.created_keys.append(key) return key except ClientError as err: logging.error( "Couldn't create your key. Here's why: %s", err.response["Error"]["Message"], ) raise
  • Untuk detail API, lihat CreateKey di AWS Referensi API SDK untuk Python (Boto3).

Ruby
SDK untuk Ruby
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode AWS.

require 'aws-sdk-kms' # v2: require 'aws-sdk' # Create a AWS KMS key. # As long we are only encrypting small amounts of data (4 KiB or less) directly, # a KMS key is fine for our purposes. # For larger amounts of data, # use the KMS key to encrypt a data encryption key (DEK). client = Aws::KMS::Client.new resp = client.create_key({ tags: [ { tag_key: 'CreatedBy', tag_value: 'ExampleUser' } ] }) puts resp.key_metadata.key_id
  • Untuk detail API, lihat CreateKey di AWS SDK untuk Ruby Referensi API.

Rust
SDK for Rust
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode AWS.

async fn make_key(client: &Client) -> Result<(), Error> { let resp = client.create_key().send().await?; let id = resp.key_metadata.as_ref().unwrap().key_id(); println!("Key: {}", id); Ok(()) }
  • Untuk detail API, lihat CreateKey di AWS Referensi SDK untuk Rust API.

SAP ABAP
SDK for SAP ABAP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode AWS.

TRY. " iv_description = 'Created by the AWS SDK for SAP ABAP' oo_result = lo_kms->createkey( iv_description = iv_description ). MESSAGE 'KMS key created successfully.' TYPE 'I'. CATCH /aws1/cx_kmskmsinternalex. MESSAGE 'An internal error occurred.' TYPE 'E'. CATCH /aws1/cx_kmslimitexceededex. MESSAGE 'Limit exceeded for KMS resources.' TYPE 'E'. ENDTRY.
  • Untuk detail API, lihat CreateKey di AWS SDK untuk referensi API SAP ABAP.

Untuk daftar lengkap AWS Panduan pengembang SDK dan contoh kode, lihat Menggunakan layanan ini dengan AWS SDK. Topik ini juga mencakup informasi tentang memulai dan detail tentang versi SDK sebelumnya.