搭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/ 最新/用戶指南/.html cli-usage-parameters-file > AWS 命令列介面使用者指南和本機檔案參數的最佳作法 < 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 KMSAWS 金鑰管理服務開發人員指南

  • 有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 SDK對於科特林API參考。

Python
SDK對於 Python(肉毒桿菌 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對於 Python(肉毒桿 3)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 SDKAPI供鐵鏽參考

有關的完整列表 AWS SDK開發人員指南和代碼示例,請參閱使用 AWS KMS 用一個 AWS SDK。本主題也包含有關入門的資訊以及舊SDK版的詳細資訊。