use aws_esdk::client as esdk_client;
use aws_esdk::material_providers::client as mpl_client;
use aws_esdk::material_providers::types::material_providers_config::MaterialProvidersConfig;
use aws_esdk::material_providers::types::AesWrappingAlg;
use aws_esdk::material_providers::types::EsdkAlgorithmSuiteId::AlgAes256GcmHkdfSha512CommitKey;
use aws_esdk::types::aws_encryption_sdk_config::AwsEncryptionSdkConfig;
use rand::TryRngCore;
use std::collections::HashMap;
pub async fn encrypt_and_decrypt_with_keyring(example_data: &str) -> Result<(), crate::BoxError> {
let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
let key_namespace: &str = "my-key-namespace";
let key_name: &str = "my-aes-key-name";
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(),
),
]);
let aes_key_bytes = generate_aes_key_bytes();
let mpl_config = MaterialProvidersConfig::builder().build()?;
let mpl = mpl_client::Client::from_conf(mpl_config)?;
let raw_aes_keyring = mpl
.create_raw_aes_keyring()
.key_name(key_name)
.key_namespace(key_namespace)
.wrapping_key(aes_key_bytes)
.wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
.send()
.await?;
let plaintext = example_data.as_bytes();
let encryption_response = esdk_client
.encrypt()
.plaintext(plaintext)
.keyring(raw_aes_keyring.clone())
.encryption_context(encryption_context.clone())
.algorithm_suite_id(AlgAes256GcmHkdfSha512CommitKey)
.send()
.await?;
let ciphertext = encryption_response
.ciphertext
.expect("Unable to unwrap ciphertext from encryption response");
assert_ne!(
ciphertext,
aws_smithy_types::Blob::new(plaintext),
"Ciphertext and plaintext data are the same. Invalid encryption"
);
let decryption_response = esdk_client
.decrypt()
.ciphertext(ciphertext)
.keyring(raw_aes_keyring)
.encryption_context(encryption_context)
.send()
.await?;
let decrypted_plaintext = decryption_response
.plaintext
.expect("Unable to unwrap plaintext from decryption response");
assert_eq!(
decrypted_plaintext,
aws_smithy_types::Blob::new(plaintext),
"Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
);
println!("Set Encryption Algorithm Suite Example Completed Successfully");
Ok(())
}
fn generate_aes_key_bytes() -> Vec<u8> {
let mut random_bytes = [0u8; 32];
rand::rngs::OsRng.try_fill_bytes(&mut random_bytes).unwrap();
random_bytes.to_vec()
}
#[tokio::test(flavor = "multi_thread")]
pub async fn test_encrypt_and_decrypt_with_keyring() -> Result<(), crate::BoxError2> {
use crate::example_utils::utils;
encrypt_and_decrypt_with_keyring(utils::TEST_EXAMPLE_DATA).await?;
Ok(())
}