View a markdown version of this page

Gunakan ReEncrypt dengan AWS SDK atau CLI - AWS Key Management Service

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan ReEncrypt dengan AWS SDK atau CLI

Contoh-contoh kode berikut menunjukkan cara menggunakan ReEncrypt.

CLI
AWS CLI

Contoh 1: Untuk mengenkripsi ulang pesan terenkripsi di bawah kunci KMS simetris yang berbeda (Linux dan macOS)

Berikut ini re-encrypt contoh menunjukkan cara yang disarankan untuk mengenkripsi ulang data dengan AWS CLI.

Berikan ciphertext dalam file.Dalam nilai --ciphertext-blob parameter, gunakan fileb:// awalan, yang memberitahu CLI untuk membaca data dari file biner. Jika file tidak ada di direktori saat ini, ketik path lengkap ke file. Untuk informasi lebih lanjut tentang membaca AWS Nilai parameter CLI dari file, lihat Memuat AWS Parameter CLI dari file di AWS Panduan Pengguna Antarmuka Baris Perintah dan Praktik Terbaik untuk Parameter File Lokal di AWS Blog Alat Baris Perintah.Tentukan kunci sumber KMS, yang mendekripsi ciphertext.The --source-key-id parameter tidak diperlukan saat mendekripsi dengan kunci KMS enkripsi simetris. AWS KMS bisa mendapatkan kunci KMS yang digunakan untuk mengenkripsi data dari metadata di blob ciphertext. Tetapi selalu merupakan praktik terbaik untuk menentukan kunci KMS yang Anda gunakan. Praktik ini memastikan bahwa Anda menggunakan kunci KMS yang Anda inginkan, dan mencegah Anda mendekripsi ciphertext secara tidak sengaja menggunakan kunci KMS yang tidak Anda percayai.Tentukan kunci KMS tujuan, yang mengenkripsi ulang data.The --destination-key-id Parameter selalu diperlukan. Contoh ini menggunakan kunci ARN, tetapi Anda dapat menggunakan pengenal kunci yang valid.Minta keluaran plaintext sebagai nilai teks. --query parameter memberitahu CLI untuk hanya mendapatkan nilai dari Plaintext bidang dari output. --output parameter mengembalikan output sebagai teks.Base64-decode plaintext dan menyimpannya dalam file. Contoh berikut menyipkan (|) nilai Plaintext parameter ke utilitas Base64, yang menerjemahkannya. Kemudian, itu mengalihkan (>) output yang didekodekan ke ExamplePlaintext berkas.

Sebelum menjalankan perintah ini, ganti contoh ID kunci dengan pengidentifikasi kunci yang valid dari AWS akun.

aws kms re-encrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --source-key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \ --destination-key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE22222 \ --query CiphertextBlob \ --output text | base64 --decode > ExampleReEncryptedFile

Perintah ini tidak menghasilkan output. Output dari re-encrypt perintah didekodekan base64 dan disimpan dalam file.

Untuk informasi lebih lanjut, lihat AWS Esentif kriptografi KMS di AWS Panduan Pengembang Layanan Manajemen Kunci.

Contoh 2: Untuk mengenkripsi ulang pesan terenkripsi di bawah kunci KMS simetris yang berbeda (prompt perintah Windows)

Berikut ini re-encrypt contoh sama dengan yang sebelumnya kecuali bahwa ia menggunakan certutil utilitas untuk Base64-decode data plaintext. Prosedur ini membutuhkan dua perintah, seperti yang ditunjukkan pada contoh berikut.

Sebelum menjalankan perintah ini, ganti contoh ID kunci dengan ID kunci yang valid dari AWS akun.

aws kms re-encrypt ^ --ciphertext-blob fileb://ExampleEncryptedFile ^ --source-key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 ^ --destination-key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE22222 ^ --query CiphertextBlob ^ --output text > ExampleReEncryptedFile.base64

Kemudian gunakan certutil utilitas.

certutil -decode ExamplePlaintextFile.base64 ExamplePlaintextFile

Output:

Input Length = 18 Output Length = 12 CertUtil: -decode command completed successfully.

Untuk informasi lebih lanjut, lihat AWS Esentif kriptografi KMS di AWS Panduan Pengembang Layanan Manajemen Kunci.

  • Untuk detail API, lihat ReEncrypt di AWS CLI Referensi Perintah.

Python
SDK untuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode 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.")
  • Untuk detail API, lihat ReEncrypt di AWS Referensi API SDK untuk Python (Boto3).

Ruby
SDK untuk Ruby
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode 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*')
  • Untuk detail API, lihat ReEncrypt di AWS SDK untuk Ruby Referensi API.

Rust
SDK for Rust
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode 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(()) }
  • Untuk detail API, lihat ReEncrypt di AWS Referensi SDK untuk Rust API.

SAP ABAP
SDK for SAP ABAP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode AWS.

TRY. " iv_source_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab' " iv_destination_key_id = 'arn:aws:kms:us-east-1:123456789012:key/5678dcba-56cd-78ef-90ab-5678901234cd' " iv_ciphertext_blob contains the encrypted data oo_result = lo_kms->reencrypt( iv_sourcekeyid = iv_source_key_id iv_destinationkeyid = iv_destination_key_id iv_ciphertextblob = iv_ciphertext_blob ). MESSAGE 'Ciphertext reencrypted successfully.' TYPE 'I'. CATCH /aws1/cx_kmsdisabledexception. MESSAGE 'The key is disabled.' TYPE 'E'. CATCH /aws1/cx_kmsincorrectkeyex. MESSAGE 'Incorrect source key for decryption.' TYPE 'E'. CATCH /aws1/cx_kmsnotfoundexception. MESSAGE 'Key not found.' TYPE 'E'. CATCH /aws1/cx_kmskmsinternalex. MESSAGE 'An internal error occurred.' TYPE 'E'. ENDTRY.
  • Untuk detail API, lihat ReEncrypt di AWS SDK untuk referensi API SAP ABAP.

Untuk daftar lengkap AWS Panduan pengembang SDK dan contoh kode, lihat Menggunakan layanan ini dengan AWS SDK. Topik ini juga mencakup informasi tentang memulai dan detail tentang versi SDK sebelumnya.