

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# AWS Encryption SDK for Rust 範例程式碼
<a name="rust-examples"></a>

下列範例顯示使用 AWS Encryption SDK for Rust 進行程式設計時所使用的基本編碼模式。具體而言，您會執行個體化 AWS Encryption SDK 和材料提供者程式庫。然後，在呼叫每個方法之前，您可以執行個體化定義方法輸入的物件。

如需示範如何在 中設定選項的範例 AWS Encryption SDK，例如指定替代演算法套件和限制加密的資料金鑰，請參閱 GitHub 上 aws-encryption-sdk 儲存庫中的 [Rust 範例](https://github.com/aws/aws-encryption-sdk-dafny/tree/mainline/AwsEncryptionSDK/runtimes/rust/examples/)。

## 在 AWS Encryption SDK for Rust 的 中加密和解密資料
<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：執行個體化材料提供者程式庫。**  
您將使用材料提供者程式庫中的方法來建立 keyring，以指定哪些金鑰保護您的資料。  

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

**步驟 4：建立 AWS KMS keyring。**  
若要建立 keyring，請使用 keyring 輸入物件呼叫 keyring 方法。此範例使用 `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：使用您在加密時所使用的相同 keyring 來解密加密的資料。**  

```
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");
```