Decrypt搭配使用 Amazon SDK或 CLI - Amazon Key Management Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Decrypt搭配使用 Amazon SDK或 CLI

以下代码示例演示如何使用 Decrypt

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

CLI
Amazon CLI

示例 1:使用对称密KMS钥解密加密消息(Linux 和 macOS)

以下decrypt命令示例演示了使用解密数据的推荐方法 Amazon CLI。此版本展示了如何使用对称KMS密钥解密数据。

在文件中提供密文。在--ciphertext-blob参数的值中,使用fileb://前缀,它告诉从二进制文件中读CLI取数据。如果文件不在当前目录中,请键入文件的完整路径。有关阅读的更多信息 Amazon CLI文件中的参数值,请参阅加载 Amazon CLI来自文件 < l https://docs.aws.amazon.com/cli/ atest/userguide/ cli-usage-parameters-file .html> 中的参数 Amazon 命令行界面用户指南和本地文件参数最佳实践< developer/-file-parameters/> https://aws.amazon.com/blogs/ 中 best-practices-for-local Amazon 命令行工具博客。指定用于解密密文的密KMS钥。使用对称密钥解密时不需要--key-id参数。KMS Amazon KMS可以从密文中的元数据中获取用于加密数据的密KMS钥的密钥 ID。但是,指定您正在使用的KMS密钥始终是最佳做法。这种做法可确保您使用所需的KMS密钥,并防止您无意中使用您不信任的密KMS钥解密密文。将纯文本输出请求为文本值。该--query参数告诉仅从输出中获取字段的值。CLI Plaintext--output 参数以 text.base64 解码格式返回明文输出并将其保存在文件中。以下示例将 Plaintext 参数的值传送(|)给 Base64 实用工具,该程序负责对其进行解码。然后,它将解码后的输出重定向(>)到 ExamplePlaintext 文件。

在运行此命令之前,请将示例密钥 ID 替换为您的有效密钥 ID Amazon account。

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

此命令不生成任何输出。decrypt 命令的输出经过 base64 解码并保存在文件中。

有关更多信息,请参阅《解密》中的 Amazon 密钥管理服务API参考

示例 2:使用对称密KMS钥解密加密邮件(Windows 命令提示符)

以下示例与前一个示例相同,不同之处在于,它使用 certutil 实用程序对明文数据进行 Base64 解码。此过程需要两个命令,如以下示例所示。

在运行此命令之前,请将示例密钥 ID 替换为您的有效密钥 ID Amazon account。

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.

有关更多信息,请参阅《解密》中的 Amazon 密钥管理服务API参考

示例 3:使用非对称密KMS钥解密加密消息(Linux 和 macOS)

以下decrypt命令示例显示如何解密使用RSA非对称KMS密钥加密的数据。

使用非对称KMS密钥时,必须使用encryption-algorithm参数,该参数指定用于加密纯文本的算法。

在运行此命令之前,请将示例密钥 ID 替换为您的有效密钥 ID Amazon account。

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 解码并保存在文件中。

有关更多信息,请参阅中的非对称密钥 Amazon KMSAmazon 密钥管理服务开发人员指南

  • 有关API详细信息,请参阅中的 “解密Amazon CLI 命令参考

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

/** * 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详细信息,请参阅中的 “解密Amazon SDK for Java 2.x API参考

Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

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详细信息,请参阅中的 “解密Amazon SDK以供API参考 Kotlin。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

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详细信息,请参阅中的 “解密Amazon SDK供参考 Python (Boto3) API。

Ruby
SDK对于 Ruby
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

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详细信息,请参阅中的 “解密Amazon SDK for Ruby API参考

Rust
SDK对于 Rust
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

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详细信息,请参阅中的 “解密Amazon SDK供API参考 Rust

有关完整列表 Amazon SDK开发者指南和代码示例,请参阅使用 Amazon KMS 用一个 Amazon SDK。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。