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

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

AWS SDK 또는 CLI와 ReEncrypt 함께 사용

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

CLI
AWS CLI

예시 1: 다른 대칭 KMS 키를 사용하여 암호화된 메시지 다시 암호화(Linux 및 macOS)

다음 re-encrypt 명령 예제는 AWS CLI를 사용하여 데이터를 다시 암호화하는 권장 방법을 보여줍니다.

파일에 사이퍼텍스트를 입력합니다. --ciphertext-blob 파라미터 값에는 바이너리 파일에서 데이터를 읽도록 CLI에 지시하는 fileb:// 접두사를 사용합니다. 파일이 현재 디렉터리에 없는 경우 파일의 전체 경로를 입력합니다. 파일에서 AWS CLI 파라미터 값을 읽는 방법에 대한 자세한 내용은 명령줄 인터페이스 사용 설명서의 파일 <https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html>에서 AWS CLI 파라미터 로드 및 명령AWS 줄 도구 블로그의 로컬 파일 파라미터 모범 사례<https://aws.amazon.com/blogs/developer/best-practices-for-local-file-parameters/>를 참조하세요. 소스 KMS 키를 지정하세요. AWS 는 사이퍼텍스트를 복호화합니다. 대칭 암호화 KMS 키로 복호화할 때는 --source-key-id 파라미터가 필요하지 않습니다. AWS KMS는 사이퍼텍스트 블롭의 메타데이터에서 데이터를 암호화하는 데 사용된 KMS 키를 가져올 수 있습니다. 그러나 사용 중인 KMS 키를 지정하는 것이 항상 좋습니다. 이렇게 하면 의도한 KMS 키를 사용할 수 있으며 신뢰하지 않는 KMS 키를 사용하여 사이퍼텍스트를 실수로 복호화하는 것을 방지할 수 있습니다. 데이터를 다시 암호화하는 대상 KMS 키를 지정하세요. --destination-key-id 파라미터는 항상 필요합니다. 이 예시에서는 키 ARN을 사용하지만 모든 유효한 키 식별자를 사용할 수 있습니다. 일반 텍스트 출력을 텍스트 값으로 요청하세요. --query 파라미터는 출력에서 Plaintext 필드 값만 가져오도록 CLI에 지시합니다. --output 파라미터는 출력을 텍스트로 반환합니다. 일반 텍스트를 Base64로 디코딩하여 파일에 저장합니다. 다음 예시에서는 Plaintext 파라미터 값을 Base64 유틸리티에 파이프(|)로 구분하며 유틸리티가 이를 디코딩합니다. 그런 다음 디코딩된 출력을 ExamplePlaintext 파일로 리디렉션(>)합니다.

이 명령을 실행하기 전에 예제 키 IDs AWS 계정의 유효한 키 식별자로 바꿉니다.

aws kms re-encrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --source-key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --destination-key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \ --query CiphertextBlob \ --output text | base64 --decode > ExampleReEncryptedFile

이 명령은 출력을 생성하지 않습니다. re-encrypt 명령의 출력은 base64로 디코딩되어 파일에 저장됩니다.

자세한 내용은 AWS Key Management Service API 참조의 ReEncrypt<https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html>를 참조하세요.

예시 2: 다른 대칭 KMS 키를 사용하여 암호화된 메시지 다시 암호화(Windows 명령 프롬프트)

다음 re-encrypt 명령 예시는 certutil 유틸리티를 사용하여 일반 텍스트 데이터를 base64로 디코딩한다는 점을 제외하면 이전 예시와 동일합니다. 이 프로시저에는 다음 예시와 같이 두 개의 명령이 필요합니다.

이 명령을 실행하기 전에 예제 키 ID를 AWS 계정의 유효한 키 ID로 바꿉니다.

aws kms re-encrypt ^ --ciphertext-blob fileb://ExampleEncryptedFile ^ --source-key-id 1234abcd-12ab-34cd-56ef-1234567890ab ^ --destination-key-id 0987dcba-09fe-87dc-65ba-ab0987654321 ^ --query CiphertextBlob ^ --output text > ExampleReEncryptedFile.base64

그런 다음 certutil 유틸리티를 사용합니다.

certutil -decode ExamplePlaintextFile.base64 ExamplePlaintextFile

출력:

Input Length = 18 Output Length = 12 CertUtil: -decode command completed successfully.

자세한 내용은 AWS Key Management Service API 참조의 ReEncrypt<https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html>를 참조하세요.

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

Python
SDK for Python (Boto3)
참고

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

class KeyEncrypt: def __init__(self, kms_client): self.kms_client = kms_client @classmethod def from_client(cls) -> "KeyEncrypt": """ Creates a KeyEncrypt instance with a default KMS client. :return: An instance of KeyEncrypt initialized with the default KMS client. """ kms_client = boto3.client("kms") return cls(kms_client) def re_encrypt(self, source_key_id, cipher_text): """ Takes ciphertext previously encrypted with one key and reencrypt it by using another key. :param source_key_id: The ARN or ID of the original key used to encrypt the ciphertext. :param cipher_text: The encrypted ciphertext. :return: The ciphertext encrypted by the second key. """ destination_key_id = input( f"Your ciphertext is currently encrypted with key {source_key_id}. " f"Enter another key ID or ARN to reencrypt it: " ) if destination_key_id != "": try: cipher_text = self.kms_client.re_encrypt( SourceKeyId=source_key_id, DestinationKeyId=destination_key_id, CiphertextBlob=cipher_text, )["CiphertextBlob"] except ClientError as err: logger.error( "Couldn't reencrypt your ciphertext. Here's why: %s", err.response["Error"]["Message"], ) else: print(f"Reencrypted your ciphertext as: {cipher_text}") return cipher_text else: print("Skipping reencryption demo.")
  • API 세부 정보는 AWS SDK for Python (Boto3) API 참조ReEncrypt를 참조하십시오.

Ruby
SDK for Ruby
참고

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

require 'aws-sdk-kms' # v2: require 'aws-sdk' # Human-readable version of the ciphertext of the data to reencrypt. blob = '01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1' sourceCiphertextBlob = [blob].pack('H*') # Replace the fictitious key ARN with a valid key ID destinationKeyId = 'arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321' client = Aws::KMS::Client.new(region: 'us-west-2') resp = client.re_encrypt({ ciphertext_blob: sourceCiphertextBlob, destination_key_id: destinationKeyId }) # Display a readable version of the resulting re-encrypted blob. puts 'Blob:' puts resp.ciphertext_blob.unpack('H*')
  • API 세부 정보는 AWS SDK for Ruby API 참조ReEncrypt를 참조하십시오.

Rust
SDK for Rust
참고

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

async fn reencrypt_string( verbose: bool, client: &Client, input_file: &str, output_file: &str, first_key: &str, new_key: &str, ) -> Result<(), Error> { // Get blob from input file // Open input text file and get contents as a string // input is a base-64 encoded string, so decode it: let data = fs::read_to_string(input_file) .map(|input_file| base64::decode(input_file).expect("invalid base 64")) .map(Blob::new); let resp = client .re_encrypt() .ciphertext_blob(data.unwrap()) .source_key_id(first_key) .destination_key_id(new_key) .send() .await?; // Did we get an encrypted blob? let blob = resp.ciphertext_blob.expect("Could not get encrypted text"); let bytes = blob.as_ref(); let s = base64::encode(bytes); let o = &output_file; let mut ofile = File::create(o).expect("unable to create file"); ofile.write_all(s.as_bytes()).expect("unable to write"); if verbose { println!("Wrote the following to {}:", output_file); println!("{}", s); } else { println!("Wrote base64-encoded output to {}", output_file); } Ok(()) }
  • API 세부 정보는 AWS SDK for Rust API 참조ReEncrypt를 참조하십시오.

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