

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

# AWS Encryption SDK 对于 Rust 的示例代码
<a name="rust-examples"></a>

以下示例显示了使用 for Rust AWS Encryption SDK 进行编程时使用的基本编码模式。具体而言，您可以实例化材料提供者库 AWS Encryption SDK 和材料提供者库。然后，在调用每个方法之前，先实例化定义该方法输入的对象。

有关展示如何在中配置选项（例如指定备用算法套件和限制加密数据密钥）的示例，请参阅 aws-encryption-sdk存储库中的 [Rust 示例](https://github.com/aws/aws-encryption-sdk-dafny/tree/mainline/AwsEncryptionSDK/runtimes/rust/examples/) GitHub。 AWS Encryption SDK

## 在 for Rust 中加密和解密数据 AWS Encryption SDK
<a name="rust-example-encrypt"></a>

此示例显示了加密和解密数据的基本模式。它使用受一个 AWS KMS 包装密钥保护的数据密钥对一个小文件进行加密。

**步骤 1：实例化. AWS Encryption SDK**  
您将使用中的方法 AWS Encryption SDK 来加密和解密数据。  

```
let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
```

**步骤 2：创建 AWS KMS 客户端。**  

```
let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
let kms_client = aws_sdk_kms::Client::new(&sdk_config);
```

**可选：创建您的加密上下文。**  

```
let encryption_context = HashMap::from([
    ("encryption".to_string(), "context".to_string()),
    ("is not".to_string(), "secret".to_string()),
    ("but adds".to_string(), "useful metadata".to_string()),
    ("that can help you".to_string(), "be confident that".to_string()),
    ("the data you are handling".to_string(), "is what you think it is".to_string()),
]);
```

**第 3 步：实例化材料提供者库。**  
您将使用材料提供程序库中的方法创建密钥环，密钥环指定哪些密钥保护您的数据。  

```
let mpl_config = MaterialProvidersConfig::builder().build()?;
let mpl = mpl_client::Client::from_conf(mpl_config)?;
```

**步骤 4：创建 AWS KMS 密钥环。**  
要创建密钥环，请使用密钥环输入对象调用密钥环方法。此示例使用`create_aws_kms_keyring()`方法并指定一个 KMS 密钥。  

```
let kms_keyring = mpl
    .create_aws_kms_keyring()
    .kms_key_id(kms_key_id)
    .kms_client(kms_client)
    .send()
    .await?;
```

**第 5 步：加密明文。**  

```
let plaintext = example_data.as_bytes();

let encryption_response = esdk_client.encrypt()
    .plaintext(plaintext)
    .keyring(kms_keyring.clone())
    .encryption_context(encryption_context.clone())
    .send()
    .await?;

let ciphertext = encryption_response
                    .ciphertext
                    .expect("Unable to unwrap ciphertext from encryption response");
```

**第 6 步：使用与加密时相同的密钥环解密您的加密数据。**  

```
let decryption_response = esdk_client.decrypt()
    .ciphertext(ciphertext)
    .keyring(kms_keyring)
    // Provide the encryption context that was supplied to the encrypt method
    .encryption_context(encryption_context)
    .send()
    .await?;

let decrypted_plaintext = decryption_response
                            .plaintext
                            .expect("Unable to unwrap plaintext from decryption response");
```