AWS SDK 또는 CLI와 CreateKey 함께 사용 - AWS Key Management Service

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

AWS SDK 또는 CLI와 CreateKey 함께 사용

다음 코드 예제는 CreateKey의 사용 방법을 보여 줍니다.

작업 예제는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

GitHub에 더 많은 내용이 있습니다. 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."); } } }
  • API에 대한 세부 정보는 AWS SDK for .NET API 참조CreateKey를 참조하세요.

CLI
AWS CLI

예제 1: KMS에서 고객 관리형 AWS KMS 키 생성

다음 create-key 예시에서는 대칭 암호화 KMS 키를 생성합니다.

대칭 암호화 키인 기본 KMS 키를 생성하기 위해 파라미터를 지정할 필요가 없습니다. 이러한 파라미터의 기본값은 대칭 암호화 키를 생성합니다.

이 명령은 키 정책을 지정하지 않으므로 KMS 키는 프로그래밍 방식으로 만든 KMS 키에 대한 기본 키 정책을 가져옵니다. 키 정책을 보려면 get-key-policy 명령을 사용합니다. 키 정책을 변경하려면 put-key-policy 명령을 사용합니다.

aws kms create-key

create-key 명령은 새 KMS 키의 키 ID 및 ARN을 포함한 키 메타데이터를 반환합니다. 이러한 값을 사용하여 다른 KMS 작업에서 AWS KMS 키를 식별할 수 있습니다. 출력에 태그가 포함되지 않습니다. KMS 키에 지정된 태그를 보려면 list-resource-tags command를 사용합니다.

출력:

{ "KeyMetadata": { "AWSAccountId": "111122223333", "Arn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "CreationDate": "2017-07-05T14:04:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "Description": "", "Enabled": true, "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "AWS_KMS" "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ] } }

참고: create-key 명령으로는 별칭을 지정할 수 없습니다. 새 KMS 키의 별칭을 만들려면 create-alias 명령을 사용합니다.

자세한 내용은 AWS Key Management Service 개발자 안내서키 생성을 참조하세요.

예시 2: 암호화 및 복호화를 위한 비대칭 RSA KMS 키 생성

다음 create-key 예시에서는 암호화 및 복호화를 위한 비대칭 RSA 키 페어가 포함된 KMS 키를 생성합니다.

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

출력:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2021-04-05T14:04:55-07:00", "CustomerMasterKeySpec": "RSA_4096", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256" ], "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "RSA_4096", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "AWS_KMS" } }

자세한 내용은 Key AWS Management Service 개발자 안내서의 AWS KMS의 비대칭 키를 참조하세요.

예시 3: 서명 및 확인을 위한 비대칭 타원 곡선 KMS 키 생성

서명 및 확인을 위해 비대칭 타원 곡선(ECC) 키 페어가 포함된 비대칭 KMS 키를 생성합니다. ECC KMS 키에 사용할 수 있는 유일한 값이 SIGN_VERIFY이더라도 --key-usage 파라미터는 필수입니다.

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

출력:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2019-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "ECC_NIST_P521", "Description": "", "Enabled": true, "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "ECC_NIST_P521", "KeyState": "Enabled", "KeyUsage": "SIGN_VERIFY", "MultiRegion": false, "Origin": "AWS_KMS", "SigningAlgorithms": [ "ECDSA_SHA_512" ] } }

자세한 내용은 Key AWS Management Service 개발자 안내서의 AWS KMS의 비대칭 키를 참조하세요.

예시 4: HMAC KMS 키 생성

다음 create-key 예시에서는 384비트 HMAC KMS 키를 생성합니다. HMAC KMS 키에 사용할 수 있는 유일한 값이더라도 --key-usage 파라미터의 GENERATE_VERIFY_MAC 값은 필수입니다.

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

출력:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2022-04-05T14:04:55-07:00", "CustomerMasterKeySpec": "HMAC_384", "Description": "", "Enabled": true, "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "HMAC_384", "KeyState": "Enabled", "KeyUsage": "GENERATE_VERIFY_MAC", "MacAlgorithms": [ "HMAC_SHA_384" ], "MultiRegion": false, "Origin": "AWS_KMS" } }

자세한 내용은 Key Management Service 개발자 안내서의 AWS KMS의 HMAC 키를 참조하세요. AWS

예시 4: 다중 리전 프라이머리 KMS 키 생성

다음 create-key 예시에서는 다중 리전 프라이머리 대칭 암호화 키를 생성합니다. 모든 파라미터의 기본값이 대칭 암호화 키를 생성하므로 이 KMS 키에는 --multi-region 파라미터만 필요합니다. AWS CLI에서 부울 파라미터가 true임을 나타내려면 파라미터 이름을 지정하면 됩니다.

aws kms create-key \ --multi-region

출력:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:111122223333:key/mrk-1234abcd12ab34cd56ef12345678990ab", "AWSAccountId": "111122223333", "CreationDate": "2021-09-02T016:15:21-09:00", "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:111122223333:key/mrk-1234abcd12ab34cd56ef12345678990ab", "Region": "us-west-2" }, "ReplicaKeys": [] }, "Origin": "AWS_KMS" } }

자세한 내용은 Key AWS Management Service 개발자 안내서의 AWS KMS의 비대칭 키를 참조하세요.

예시 5: 가져온 키 구성 요소에 대한 KMS 키 생성

다음 create-key 예시에서는 키 구성 요소 없이 KMS 키를 생성합니다. 작업이 완료되면 자체 키 구성 요소를 KMS 키로 가져올 수 있습니다. 이 KMS 키를 생성하려면 --origin 파라미터를 EXTERNAL로 설정하세요.

aws kms create-key \ --origin EXTERNAL

출력:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2019-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "Description": "", "Enabled": false, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "PendingImport", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "EXTERNAL" } }

자세한 내용은 Key Management Service 개발자 안내서의 AWS KMS 키에서 키 구성 요소 가져오기를 참조하세요. AWS

예제 6: AWS CloudHSM 키 스토어에서 KMS 키 생성

다음 create-key 예제에서는 지정된 AWS CloudHSM 키 스토어에 KMS 키를 생성합니다. 작업은 KMS 키와 해당 메타데이터를 AWS KMS에 생성하고 사용자 지정 키 스토어와 연결된 AWS CloudHSM 클러스터에 키 구성 요소를 생성합니다. --custom-key-store-id--origin 파라미터가 필요합니다.

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

출력:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CloudHsmClusterId": "cluster-1a23b4cdefg", "CreationDate": "2019-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "CustomKeyStoreId": "cks-1234567890abcdef0", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "AWS_CLOUDHSM" } }

자세한 내용은 AWS Key Management Service 개발자 안내서AWS CloudHSM 키 저장소를 참조하세요.

예시 7: 외부 키 저장소에 KMS 키 생성

다음 create-key 예시에서는 지정된 외부 키 저장소에 KMS 키를 생성합니다. 이 명령에는 --custom-key-store-id, --origin, --xks-key-id 파라미터가 필요합니다.

--xks-key-id 파라미터는 외부 키 관리자에 있는 기존 대칭 암호화 키의 ID를 지정합니다. 이 키는 KMS 키의 외부 키 구성 요소 역할을 합니다. --origin 파라미터의 값은 EXTERNAL_KEY_STORE여야 합니다. custom-key-store-id 파라미터는 외부 키 저장소 프록시에 연결된 외부 키 저장소를 식별해야 합니다.

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

출력:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2022-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "CustomKeyStoreId": "cks-9876543210fedcba9", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "EXTERNAL_KEY_STORE", "XksKeyConfiguration": { "Id": "bb8562717f809024" } } }

자세한 내용은 AWS Key Management Service 개발자 안내서외부 키 저장소를 참조하세요.

  • API 세부 정보는 AWS CLI 명령 참조의 CreateKey를 참조하세요.

Java
SDK for Java 2.x
참고

GitHub에 더 많은 내용이 있습니다. 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); }); }
  • API 세부 정보는 AWS SDK for Java 2.x API 참조CreateKey를 참조하십시오.

Kotlin
SDK for Kotlin
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

suspend fun createKey(keyDesc: String?): String? { val request = CreateKeyRequest { description = keyDesc customerMasterKeySpec = CustomerMasterKeySpec.SymmetricDefault keyUsage = KeyUsageType.fromValue("ENCRYPT_DECRYPT") } KmsClient { 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 } }
  • API 세부 정보는 AWS SDK for Kotlin API 참조CreateKey를 참조하십시오.

PHP
SDK for PHP
참고

GitHub에 더 많은 내용이 있습니다. 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; } }
  • API에 대한 세부 정보는 AWS SDK for PHP API 참조CreateKey를 참조하세요.

Python
SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. 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
  • API 세부 정보는 AWS SDK for Python (Boto3) API 참조CreateKey를 참조하십시오.

Ruby
SDK for Ruby
참고

GitHub에 더 많은 내용이 있습니다. 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
  • API 세부 정보는 AWS SDK for Ruby API 참조CreateKey를 참조하십시오.

Rust
SDK for Rust
참고

GitHub에 더 많은 내용이 있습니다. 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(()) }
  • API 세부 정보는 AWS SDK for Rust API 참조CreateKey를 참조하십시오.

AWS SDK 개발자 가이드 및 코드 예제의 전체 목록은 섹션을 참조하세요에서이 서비스 사용 AWS SDK. 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.