ReEncrypt 搭配 AWS SDK或 使用 CLI - AWS Key Management Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

ReEncrypt 搭配 AWS SDK或 使用 CLI

下列程式碼範例示範如何使用 ReEncrypt

CLI
AWS CLI

範例 1:在不同的對稱KMS金鑰 (Linux 和 macOS ) 下重新加密訊息。

下列re-encrypt命令範例示範使用 重新加密資料的建議方法 AWS CLI。

在 file.In 中提供 --ciphertext-blob 參數值的密碼文字,使用 fileb:// 字首,告訴 讀取二進位檔案CLI的資料。如果檔案不在目前的目錄中,請輸入檔案的完整路徑。如需從檔案讀取 AWS CLI參數值的詳細資訊,請參閱 AWS 命令列介面使用者指南中的從檔案載入 AWS CLI參數 <https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html>,以及 AWS Command Line Tool 部落格 中的本機檔案參數<https://aws.amazon.com/blogs/developer/best-practices-for-local-file-parameters/> 的最佳實務。指定解密加密文字的來源KMS金鑰。使用對稱加密KMS金鑰解密時不需要 --source-key-id 參數。 AWS KMS 可以取得用來加密加密加密加密文字 Blob 中中繼資料資料的KMS金鑰。但是,指定您正在使用的KMS金鑰始終是最佳實務。此做法可確保您使用您打算使用的KMS金鑰,並防止您使用不信任的KMS金鑰意外解密密碼文字。指定目的地KMS金鑰,重新加密資料。--destination-key-id參數始終是必要的。此範例使用金鑰 ARN,但您可以使用任何有效的金鑰識別符。請求純文字輸出作為文字值。 --query 參數會告訴 僅從輸出CLI取得Plaintext欄位的值。--output 參數會以 text.Base64 形式傳回輸出。將純文字解碼並儲存在檔案中。下列範例會將 Plaintext 參數的值 (|) 引導至 Base64 公用程式,以解碼該參數。然後,它會將解碼的輸出重新導向 (>) 至 ExamplePlaintext 檔案。

在執行此命令之前,請將範例金鑰取代IDs為來自您 AWS 帳戶的有效金鑰識別符。

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 解碼,並儲存在 檔案中。

如需詳細資訊,請參閱 AWS 金鑰管理服務API參考 中的 ReEncrypt <https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html。

範例 2:在不同的對稱KMS金鑰 (Windows 命令提示) 下重新加密訊息。

下列re-encrypt命令範例與上一個命令範例相同,但它使用 certutil 公用程式對純文字資料進行 Base64-decode。此程序需要兩個命令,如下列範例所示。

在執行此命令之前,請將範例金鑰 ID 取代為來自您 AWS 帳戶的有效金鑰 ID。

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.

如需詳細資訊,請參閱 AWS 金鑰管理服務API參考 中的 ReEncrypt <https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html。

  • 如需API詳細資訊,請參閱 命令參考 ReEncrypt中的 。 AWS CLI

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 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 中的 AWS SDK for Python (Boto3) API參考

Ruby
SDK 適用於 Ruby
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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中的 。 AWS SDK for Ruby API

Rust
SDK for Rust
注意

還有更多 。 GitHub尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 中的 AWS SDK for Rust API參考

如需開發人員指南和程式碼範例的完整清單 AWS SDK,請參閱 將此服務與 搭配使用 AWS SDK。本主題也包含有關入門的資訊,以及先前SDK版本的詳細資訊。