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

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

ReEncrypt搭配使用 Amazon SDK或 CLI

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

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

CLI
Amazon CLI

示例 1:使用不同的对称密KMS钥(Linux 和 macOS)重新加密加密消息。

以下re-encrypt命令示例演示了使用重新加密数据的推荐方法 Amazon CLI.

在文件中提供密文。在--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钥。使用对称加密密钥解密时不需要--source-key-id参数。KMS Amazon KMS可以从密文 blob 中的元数据中获取用于加密数据的密KMS钥。但是,指定您正在使用的KMS密钥始终是最佳做法。这种做法可确保您使用所需的KMS密钥,并防止您无意中使用您不信任的密钥解密密文。请指定目标密KMS钥,它会重新加密数据。参数始终为必填KMS项。--destination-key-id此示例使用密钥ARN,但您可以使用任何有效的密钥标识符。将纯文本输出请求为文本值。该--query参数告诉仅从输出中CLI获取字段的值。Plaintext--output 参数以 text.base64 解码格式返回明文输出并将其保存在文件中。以下示例将 Plaintext 参数的值传送(|)给 Base64 实用工具,该程序负责对其进行解码。然后,它将解码后的输出重定向(>)到 ExamplePlaintext 文件。

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

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

有关更多信息,请参阅 ReEncrypt < https://docs.aws.amazon.com/kms/ latestAPIReference//API_ReEncrypt.html 中的 Amazon 密钥管理服务API参考

示例 2:使用不同的对称密KMS钥重新加密加密邮件(Windows 命令提示符)。

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

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

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.

有关更多信息,请参阅 ReEncrypt < https://docs.aws.amazon.com/kms/ latestAPIReference//API_ReEncrypt.html 中的 Amazon 密钥管理服务API参考

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

Python
SDK适用于 Python (Boto3)
注意

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

class KeyEncrypt: def __init__(self, kms_client): self.kms_client = 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详细信息,请参阅ReEncrypt中的 Amazon SDK供参考 Python (Boto3) API。

Ruby
SDK对于 Ruby
注意

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

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

Rust
SDK对于 Rust
注意

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

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

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