View a markdown version of this page

Gunakan Mendekripsi 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 Mendekripsi dengan AWS SDK atau CLI

Contoh-contoh kode berikut menunjukkan cara menggunakan Decrypt.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

CLI
AWS CLI

Contoh 1: Untuk mendekripsi pesan terenkripsi dengan kunci KMS simetris (Linux dan macOS)

Berikut ini decrypt contoh menunjukkan cara yang disarankan untuk mendekripsi data dengan AWS CLI. Versi ini menunjukkan cara mendekripsi data di bawah kunci KMS simetris.

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 <https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html> di AWS Panduan Pengguna Antarmuka Baris Perintah dan Praktik Terbaik untuk Parameter File Lokal <https://aws.amazon.com/blogs/developer/best-practices-for-local-file-parameters/> di AWS Blog Alat Baris Perintah.Tentukan kunci KMS untuk mendekripsi CipherText.The --key-id parameter tidak diperlukan saat mendekripsi dengan kunci KMS simetris. AWS KMS bisa mendapatkan ID kunci dari kunci KMS yang digunakan untuk mengenkripsi data dari metadata dalam 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.Minta keluaran plaintext sebagai nilai teks.The --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 ID kunci yang valid dari AWS akun.

aws kms decrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \ --output text \ --query Plaintext | base64 --decode > ExamplePlaintextFile

Perintah ini tidak menghasilkan output. Output dari decrypt 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 mendekripsi pesan terenkripsi dengan kunci KMS simetris (prompt perintah Windows)

Berikut ini decrypt 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 decrypt ^ --ciphertext-blob fileb://ExampleEncryptedFile ^ --key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 ^ --output text ^ --query Plaintext > ExamplePlaintextFile.base64

Jalankan perintah certutil.

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.

Contoh 3: Untuk mendekripsi pesan terenkripsi dengan kunci KMS asimetris (Linux dan macOS)

Berikut ini decrypt contoh menunjukkan cara mendekripsi data yang dienkripsi di bawah kunci KMS asimetris RSA.

Saat menggunakan kunci KMS asimetris, encryption-algorithm parameter, yang menentukan algoritma yang digunakan untuk mengenkripsi plaintext, diperlukan.

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

aws kms decrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE22222 \ --encryption-algorithm RSAES_OAEP_SHA_256 \ --output text \ --query Plaintext | base64 --decode > ExamplePlaintextFile

Perintah ini tidak menghasilkan output. Output dari decrypt perintah didekodekan base64 dan disimpan dalam file.

Untuk informasi lebih lanjut, lihat Kunci asimetris di AWS KM di AWS Panduan Pengembang Layanan Manajemen Kunci.

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

Java
SDK untuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode 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)); }
  • Untuk detail API, lihat Mendekripsi di AWS SDK for Java 2.x Referensi API.

Kotlin
SDK untuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di Repositori Contoh Kode 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.fromEnvironment { 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?, ) { val decryptRequest = DecryptRequest { ciphertextBlob = encryptedDataVal keyId = keyIdVal } KmsClient { region = "us-west-2" }.use { kmsClient -> val decryptResponse = kmsClient.decrypt(decryptRequest) val myVal = decryptResponse.plaintext // Print the decrypted data. print(myVal) } }
  • Untuk detail API, lihat Mendekripsi di AWS SDK untuk referensi API Kotlin.

PHP
SDK untuk PHP
catatan

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

/*** * @param string $keyId * @param string $ciphertext * @param string $algorithm * @return Result */ public function decrypt(string $keyId, string $ciphertext, string $algorithm = "SYMMETRIC_DEFAULT") { try{ return $this->client->decrypt([ 'CiphertextBlob' => $ciphertext, 'EncryptionAlgorithm' => $algorithm, 'KeyId' => $keyId, ]); }catch(KmsException $caught){ echo "There was a problem decrypting the data: {$caught->getAwsErrorMessage()}\n"; throw $caught; } }
  • Untuk detail API, lihat Mendekripsi di AWS SDK untuk PHP Referensi API.

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 decrypt(self, key_id: str, cipher_text: bytes) -> str: """ 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. :return: The decrypted text. """ try: return self.kms_client.decrypt(KeyId=key_id, CiphertextBlob=cipher_text)[ "Plaintext" ].decode() except ClientError as err: logger.error( "Couldn't decrypt your ciphertext. Here's why: %s", err.response["Error"]["Message"], ) raise
  • Untuk detail API, lihat Mendekripsi 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' # 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
  • Untuk detail API, lihat Mendekripsi 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 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(()) }
  • Untuk detail API, lihat Mendekripsi 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_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab' " iv_ciphertext_blob contains the encrypted data oo_result = lo_kms->decrypt( iv_keyid = iv_key_id iv_ciphertextblob = iv_ciphertext_blob ). MESSAGE 'Text decrypted successfully.' TYPE 'I'. CATCH /aws1/cx_kmsdisabledexception. MESSAGE 'The key is disabled.' TYPE 'E'. CATCH /aws1/cx_kmsincorrectkeyex. MESSAGE 'Incorrect 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 Mendekripsi 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.