

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

# `Decrypt`与 AWS SDK 或 CLI 配合使用
<a name="example_kms_Decrypt_section"></a>

以下代码示例演示如何使用 `Decrypt`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_kms_Scenario_Basics_section.md) 

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

**AWS CLI**  
**示例 1：使用对称 KMS 密钥解密加密消息（Linux 和 macOS）**  
以下`decrypt`命令示例演示了使用 CLI AWS 解密数据的推荐方法。此版本演示了如何使用对称 KMS 密钥解密数据。  
在文件中提供加密文字。在 `--ciphertext-blob` 参数的值中，使用 `fileb://` 前缀，它将指示 CLI 从二进制文件中读取数据。如果文件不在当前目录中，请键入文件的完整路径。有关从文件读取 AWS CLI 参数值的更多信息，请参阅*AWS 命令行界面用户指南中的从文件中加载 AWS CLI 参数 < https://docs.aws.amazon.com/cli/ latest/userguide/cli-usage-parameters-file .html> 和AWS 命令行**工具博客*中的本地文件参数最佳实践 < dev https://aws.amazon.com/blogs/ eloper/ best-practices-for-local-file-parameters/>。指定 KMS 密钥来解密密文。使用对称 KMS 密钥解密时不需要参数。`--key-id` AWS KMS 可以从密文中的元数据中获取用于加密数据的 KMS 密钥的密钥 ID。但是，指定您正在使用的 KMS 密钥始终是最佳实践。此做法可确保您使用预期的 KMS 密钥，并防止您意外使用不信任的 KMS 密钥解密加密文字。以文本值请求明文输出。`--query` 参数指示 CLI 仅从输出中获取 `Plaintext` 字段的值。`--output` 参数以 text.base64 解码格式返回明文输出并将其保存在文件中。以下示例将 `Plaintext` 参数的值传送（\$1）给 Base64 实用程序，该程序负责对其进行解码。然后，它将解码后的输出重定向（>）到 `ExamplePlaintext` 文件。  
在运行此命令之前，请将示例密钥 ID 替换为 AWS 账户中的有效密钥 ID。  

```
aws kms decrypt \
    --ciphertext-blob fileb://ExampleEncryptedFile \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --output text \
    --query Plaintext | base64 \
    --decode > ExamplePlaintextFile
```
此命令不生成任何输出。`decrypt` 命令的输出经过 base64 解码并保存在文件中。  
有关更多信息，请参阅《AWS 密钥管理服务 API Reference》**中的[解密](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html)。  
**示例 2：使用对称 KMS 密钥解密加密消息（Windows 命令提示符）**  
以下示例与前一个示例相同，不同之处在于，它使用 `certutil` 实用程序对明文数据进行 Base64 解码。此过程需要两个命令，如以下示例所示。  
在运行此命令之前，请将示例密钥 ID 替换为 AWS 账户中的有效密钥 ID。  

```
aws kms decrypt ^
    --ciphertext-blob fileb://ExampleEncryptedFile ^
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab ^
    --output text ^
    --query Plaintext > ExamplePlaintextFile.base64
```
运行 `certutil` 命令。  

```
certutil -decode ExamplePlaintextFile.base64 ExamplePlaintextFile
```
输出：  

```
Input Length = 18
Output Length = 12
CertUtil: -decode command completed successfully.
```
有关更多信息，请参阅《AWS 密钥管理服务 API Reference》**中的[解密](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html)。  
**示例 3：使用非对称 KMS 密钥解密加密消息（Linux 和 macOS）**  
以下 `decrypt` 命令示例演示如何解密在 RSA 非对称 KMS 密钥下加密的数据。  
使用非对称 KMS 密钥时，需要 `encryption-algorithm` 参数，以指定用于加密明文的算法。  
在运行此命令之前，请将示例密钥 ID 替换为 AWS 账户中的有效密钥 ID。  

```
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
```
此命令不生成任何输出。`decrypt` 命令的输出经过 base64 解码并保存在文件中。  
有关更多信息，请参阅《[密钥管理服务开发人员指南》中的 AWS KMS 中的非对称AWS](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)*密钥*。  
+  有关 API 详细信息，请参阅《AWS CLI 命令参考》**中的[解密](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/decrypt.html)。

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

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [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));
    }
```
+  有关 API 详细信息，请参阅《AWS SDK for Java 2.x API Reference》**中的 [Decrypt](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/Decrypt)。

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

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [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)
    }
}
```
+  有关 API 详细信息，请参阅《AWS SDK for Kotlin API Reference》**中的 [Decrypt](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

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

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [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;
        }
    }
```
+  有关 API 详细信息，请参阅《适用于 PHP 的 AWS SDK API Reference》**中的 [Decrypt](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/Decrypt)。

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

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [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
```
+  有关 API 详细信息，请参阅《AWS SDK for Python (Boto3) API Reference》**中的 [Decrypt](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/Decrypt)。

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

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [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
```
+  有关 API 详细信息，请参阅《适用于 Ruby 的 AWS SDK API Reference》**中的 [Decrypt](https://docs.aws.amazon.com/goto/SdkForRubyV3/kms-2014-11-01/Decrypt)。

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

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [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(())
}
```
+  有关 API 详细信息，请参阅《AWS SDK for Rust API Reference》**中的 [Decrypt](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.decrypt)。

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

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [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.
```
+  有关 API 的详细信息，请参阅在 SAP 的 *AWS SDK 中[解密](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html) ABAP AP* I 参考。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。