

Ada lebih banyak contoh AWS SDK yang tersedia di repo Contoh [SDK AWS Doc](https://github.com/awsdocs/aws-doc-sdk-examples). GitHub 

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

# Gunakan `Decrypt` dengan AWS SDK atau CLI
<a name="kms_example_kms_Decrypt_section"></a>

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: 
+  [Pelajari dasar-dasarnya](kms_example_kms_Scenario_Basics_section.md) 

------
#### [ CLI ]

**AWS CLI**  
**Contoh 1: Untuk mendekripsi pesan terenkripsi dengan kunci KMS simetris (Linux dan macOS)**  
Contoh `decrypt` perintah berikut menunjukkan cara yang disarankan untuk mendekripsi data dengan CLI. AWS 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 nilai parameter AWS CLI dari file, lihat Memuat parameter AWS CLI dari file < https://docs.aws.amazon.com/cli/ latest/userguide/cli - usage-parameters-file .html> di *Panduan Pengguna Antarmuka Baris AWS Perintah dan Praktik Terbaik untuk Parameter File Lokal< https://aws.amazon.com/blogs/ pengembang/ best-practices-for-local -file-parameters/> di *Blog Alat Baris* Perintah*. Tentukan kunci KMS untuk mendekripsi ciphertext. Parameter tidak diperlukan saat AWS mendekripsi dengan kunci KMS simetris. `--key-id` 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. Praktek ini memastikan bahwa Anda menggunakan kunci KMS yang Anda inginkan, dan mencegah Anda dari secara tidak sengaja mendekripsi ciphertext menggunakan kunci KMS yang tidak Anda percayai. Minta output plaintext sebagai nilai teks.Parameter `--query` memberitahu CLI untuk mendapatkan hanya nilai bidang dari output. `Plaintext` `--output`Parameter mengembalikan output sebagai text.base64-decode plaintext dan menyimpannya dalam file.Contoh berikut pipa (\$1) nilai `Plaintext` parameter ke utilitas Base64, yang menerjemahkan itu. Kemudian, itu mengalihkan (>) output yang diterjemahkan ke file. `ExamplePlaintext`  
Sebelum menjalankan perintah ini, ganti ID kunci contoh dengan ID kunci yang valid dari AWS akun Anda.  

```
aws kms decrypt \
    --ciphertext-blob fileb://ExampleEncryptedFile \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --output text \
    --query Plaintext | base64 \
    --decode > ExamplePlaintextFile
```
Perintah ini tidak menghasilkan output. Output dari `decrypt` perintah adalah base64-decoded dan disimpan dalam file.  
Untuk informasi selengkapnya, lihat [Mendekripsi](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) di Referensi *API Layanan Manajemen AWS Kunci*.  
**Contoh 2: Untuk mendekripsi pesan terenkripsi dengan tombol KMS simetris (prompt perintah Windows)**  
Contoh berikut adalah 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 ID kunci contoh dengan ID kunci yang valid dari AWS akun Anda.  

```
aws kms decrypt ^
    --ciphertext-blob fileb://ExampleEncryptedFile ^
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab ^
    --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 selengkapnya, lihat [Mendekripsi](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) di Referensi *API Layanan Manajemen AWS Kunci*.  
**Contoh 3: Untuk mendekripsi pesan terenkripsi dengan kunci KMS asimetris (Linux dan macOS)**  
Contoh `decrypt` perintah berikut 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 ID kunci contoh dengan ID kunci yang valid dari AWS akun Anda.  

```
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
```
Perintah ini tidak menghasilkan output. Output dari `decrypt` perintah adalah base64-decoded dan disimpan dalam file.  
Untuk informasi selengkapnya, lihat [Kunci asimetris di AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) di Panduan *Pengembang Layanan Manajemen AWS Kunci*.  
+  Untuk detail API, lihat [Mendekripsi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/decrypt.html) di Referensi *AWS CLI Perintah*. 

------
#### [ Java ]

**SDK untuk Java 2.x**  
 Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di [Repositori Contoh Kode AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples). 

```
    /**
     * 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](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/Decrypt) di Referensi *AWS SDK for Java 2.x API*. 

------
#### [ Kotlin ]

**SDK untuk Kotlin**  
 Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di [Repositori Contoh Kode AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples). 

```
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](https://sdk.amazonaws.com/kotlin/api/latest/index.html) di *AWS SDK untuk referensi API Kotlin*. 

------
#### [ PHP ]

**SDK untuk PHP**  
 Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di [Repositori Contoh Kode AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples). 

```
    /***
     * @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](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/Decrypt) di Referensi *AWS SDK untuk PHP API*. 

------
#### [ Python ]

**SDK untuk Python (Boto3)**  
 Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di [Repositori Contoh Kode AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples). 

```
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](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/Decrypt) dalam *AWS SDK for Python (Boto3)* Referensi API. 

------
#### [ Ruby ]

**SDK untuk Ruby**  
 Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di [Repositori Contoh Kode AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/kms#code-examples). 

```
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](https://docs.aws.amazon.com/goto/SdkForRubyV3/kms-2014-11-01/Decrypt) di Referensi *AWS SDK untuk Ruby API*. 

------
#### [ Rust ]

**SDK for Rust**  
 Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di [Repositori Contoh Kode AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kms#code-examples). 

```
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](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.decrypt) di *AWS SDK untuk referensi API Rust*. 

------
#### [ SAP ABAP ]

**SDK for SAP ABAP**  
 Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di [Repositori Contoh Kode AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples). 

```
    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](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) di *AWS SDK untuk referensi SAP ABAP* API. 

------