다음과 Decrypt 함께 사용하십시오. AWS SDK또는 CLI - AWS Key Management Service

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

다음과 Decrypt 함께 사용하십시오. AWS SDK또는 CLI

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

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

CLI
AWS CLI

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

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

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

이 명령을 실행하기 전에 예제 키 ID를 사용자의 유효한 키 ID로 바꾸십시오. AWS 계정.

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

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

자세한 내용은 에서 암호 해독을 참조하십시오. AWS 키 관리 서비스 API 참조.

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

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

이 명령을 실행하기 전에 예제 키 ID를 사용자 소유의 유효한 키 ID로 바꾸십시오. AWS 계정.

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 키 관리 서비스 API 참조.

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

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

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

이 명령을 실행하기 전에 예제 키 ID를 사용자의 유효한 키 ID로 바꾸십시오. AWS 계정.

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로 디코딩되어 파일에 저장됩니다.

자세한 내용은 다음 비대칭 키를 참조하십시오. AWS KMS에서 AWS 키 관리 서비스 개발자 가이드.

  • 자세한 API 내용은 암호 해독을 참조하십시오. AWS CLI 커맨드 레퍼런스.

Java
SDK자바 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참조.

Kotlin
SDK코틀린의 경우
참고

더 많은 정보가 있습니다. 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?, path: String, ) { val decryptRequest = DecryptRequest { ciphertextBlob = encryptedDataVal keyId = keyIdVal } KmsClient { region = "us-west-2" }.use { kmsClient -> val decryptResponse = kmsClient.decrypt(decryptRequest) val myVal = decryptResponse.plaintext // Write the decrypted data to a file. if (myVal != null) { File(path).writeBytes(myVal) } } }
  • 자세한 API 내용은 암호 해독을 참조하십시오. AWS SDKKotlin API 참조용.

Python
SDK파이썬용 (보토3)
참고

더 많은 정보가 있습니다. GitHub 전체 예제를 찾아 설치 및 실행 방법을 알아보십시오. AWS 코드 예제 리포지토리.

class KeyEncrypt: def __init__(self, kms_client): self.kms_client = kms_client def decrypt(self, key_id, cipher_text): """ 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. """ answer = input("Ready to decrypt your ciphertext (y/n)? ") if answer.lower() == "y": try: text = 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"], ) else: print(f"Your plaintext is {text.decode()}") else: print("Skipping decryption demo.")
  • 자세한 API 내용은 암호 해독을 참조하십시오. AWS SDK파이썬 (Boto3) API 참조용.

Ruby
SDK루비의 경우
참고

더 많은 정보가 있습니다. 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참조.

Rust
SDK러스트의 경우
참고

더 많은 정보가 있습니다 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 SDKRust API 참조용입니다.

전체 목록은 다음과 같습니다. AWS SDK개발자 가이드 및 코드 예제는 을 참조하십시오사용 AWS KMS 와 함께 AWS SDK. 이 항목에는 시작에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.