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

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

AWS SDK 또는 CLI와 Decrypt 함께 사용

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

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

CLI
AWS CLI

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

다음 decrypt 명령 예제는 AWS CLI를 사용하여 데이터를 해독하는 권장 방법을 보여줍니다. 이 버전은 대칭 KMS 키로 데이터를 복호화하는 방법을 보여줍니다.

파일에 사이퍼텍스트를 입력합니다. --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 키를 지정하세요. 대칭 KMS 키로 복호화할 때 --key-id 파라미터가 필요하지 않습니다. AWS KMS는 암호텍스트의 메타데이터에서 데이터를 암호화하는 데 사용된 KMS 키의 키 ID를 가져올 수 있습니다. AWS 그러나 사용 중인 KMS 키를 지정하는 것이 항상 좋습니다. 이렇게 하면 의도한 KMS 키를 사용할 수 있으며 신뢰하지 않는 KMS 키를 사용하여 사이퍼텍스트를 실수로 복호화하는 것을 방지할 수 있습니다. 일반 텍스트 출력을 텍스트 값으로 요청하세요. --query 파라미터는 CLI에 출력에서 Plaintext 필드 값만 가져오도록 지시합니다. --output 파라미터는 출력을 텍스트로 반환합니다. 일반 텍스트를 Base64로 디코딩하여 파일에 저장합니다. 다음 예시에서는 Plaintext 파라미터 값을 Base64 유틸리티에 파이프(|)로 구분하며 유틸리티가 이를 디코딩합니다. 그런 다음 디코딩된 출력을 ExamplePlaintext 파일로 리디렉션(>)합니다.

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

aws kms decrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --output text \ --query Plaintext | base64 \ --decode > ExamplePlaintextFile

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

자세한 내용은 AWS Key Management Service API 참조암호화 해제를 참조하세요.

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

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

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

aws kms decrypt ^ --ciphertext-blob fileb://ExampleEncryptedFile ^ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab ^ --output text ^ --query Plaintext > ExamplePlaintextFile.base64

certutil 명령을 실행합니다.

certutil -decode ExamplePlaintextFile.base64 ExamplePlaintextFile

출력:

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

자세한 내용은 AWS Key Management Service API 참조암호화 해제를 참조하세요.

예시 3: 비대칭 KMS 키를 사용하여 암호화된 메시지 복호화(Linux 및 macOS)

다음 decrypt 명령 예시에서는 RSA 비대칭 KMS 키로 암호화된 데이터를 복호화하는 방법을 보여줍니다.

비대칭 KMS 키를 사용하는 경우 일반 텍스트를 암호화하는 데 사용되는 알고리즘을 지정하는 encryption-algorithm 파라미터가 필요합니다.

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

aws kms decrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \ --encryption-algorithm RSAES_OAEP_SHA_256 \ --output text \ --query Plaintext | base64 \ --decode > ExamplePlaintextFile

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

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

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

Java
SDK for Java 2.x
참고

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

/** * Asynchronously decrypts the given encrypted data using the specified key ID. * * @param encryptedData The encrypted data to be decrypted. * @param keyId The ID of the key to be used for decryption. * @return A CompletableFuture that, when completed, will contain the decrypted data as a String. * If an error occurs during the decryption process, the CompletableFuture will complete * exceptionally with the error, and the method will return an empty String. */ public CompletableFuture<String> decryptDataAsync(SdkBytes encryptedData, String keyId) { DecryptRequest decryptRequest = DecryptRequest.builder() .ciphertextBlob(encryptedData) .keyId(keyId) .build(); CompletableFuture<DecryptResponse> responseFuture = getAsyncClient().decrypt(decryptRequest); responseFuture.whenComplete((decryptResponse, exception) -> { if (exception == null) { logger.info("Data decrypted successfully for key ID: " + keyId); } else { if (exception instanceof KmsException kmsEx) { throw new RuntimeException("KMS error occurred while decrypting data: " + kmsEx.getMessage(), kmsEx); } else { throw new RuntimeException("An unexpected error occurred while decrypting data: " + exception.getMessage(), exception); } } }); return responseFuture.thenApply(decryptResponse -> decryptResponse.plaintext().asString(StandardCharsets.UTF_8)); }
  • API 세부 정보는 AWS SDK for Java 2.x API 참조Decrypt를 참조하십시오.

Kotlin
SDK for Kotlin
참고

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

suspend fun encryptData(keyIdValue: String): ByteArray? { val text = "This is the text to encrypt by using the AWS KMS Service" val myBytes: ByteArray = text.toByteArray() val encryptRequest = EncryptRequest { keyId = keyIdValue plaintext = myBytes } KmsClient { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.encrypt(encryptRequest) val algorithm: String = response.encryptionAlgorithm.toString() println("The encryption algorithm is $algorithm") // Return the encrypted data. return response.ciphertextBlob } } suspend fun decryptData( encryptedDataVal: ByteArray?, keyIdVal: String?, ) { val decryptRequest = DecryptRequest { ciphertextBlob = encryptedDataVal keyId = keyIdVal } KmsClient { region = "us-west-2" }.use { kmsClient -> val decryptResponse = kmsClient.decrypt(decryptRequest) val myVal = decryptResponse.plaintext // Print the decrypted data. print(myVal) } }
  • API 세부 정보는 AWS SDK for Kotlin API 참조Decrypt를 참조하십시오.

PHP
SDK for PHP
참고

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

/*** * @param string $keyId * @param string $ciphertext * @param string $algorithm * @return Result */ public function decrypt(string $keyId, string $ciphertext, string $algorithm = "SYMMETRIC_DEFAULT") { try{ return $this->client->decrypt([ 'CiphertextBlob' => $ciphertext, 'EncryptionAlgorithm' => $algorithm, 'KeyId' => $keyId, ]); }catch(KmsException $caught){ echo "There was a problem decrypting the data: {$caught->getAwsErrorMessage()}\n"; throw $caught; } }
  • API에 대한 세부 정보는 AWS SDK for PHP API 참조Decrypt를 참조하세요.

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 decrypt(self, key_id: str, cipher_text: str) -> bytes: """ Decrypts text previously encrypted with a key. :param key_id: The ARN or ID of the key used to decrypt the data. :param cipher_text: The encrypted text to decrypt. :return: The decrypted text. """ try: return self.kms_client.decrypt(KeyId=key_id, CiphertextBlob=cipher_text)[ "Plaintext" ] except ClientError as err: logger.error( "Couldn't decrypt your ciphertext. Here's why: %s", err.response["Error"]["Message"], ) raise
  • API 세부 정보는 AWS SDK for Python (Boto3) API 참조Decrypt를 참조하십시오.

Ruby
SDK for Ruby
참고

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

require 'aws-sdk-kms' # v2: require 'aws-sdk' # Decrypted blob blob = '01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1' blob_packed = [blob].pack('H*') client = Aws::KMS::Client.new(region: 'us-west-2') resp = client.decrypt({ ciphertext_blob: blob_packed }) puts 'Raw text: ' puts resp.plaintext
  • API 세부 정보는 AWS SDK for Ruby API 참조Decrypt를 참조하십시오.

Rust
SDK for Rust
참고

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

async fn decrypt_key(client: &Client, key: &str, filename: &str) -> Result<(), Error> { // 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(filename) .map(|input| { base64::decode(input).expect("Input file does not contain valid base 64 characters.") }) .map(Blob::new); let resp = client .decrypt() .key_id(key) .ciphertext_blob(data.unwrap()) .send() .await?; let inner = resp.plaintext.unwrap(); let bytes = inner.as_ref(); let s = String::from_utf8(bytes.to_vec()).expect("Could not convert to UTF-8"); println!(); println!("Decoded string:"); println!("{}", s); Ok(()) }
  • API 세부 정보는 AWS SDK for Rust API 참조Decrypt를 참조하십시오.

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