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::types::aws_encryption_sdk_config::AwsEncryptionSdkConfig;
use std::collections::HashMap;
pub async fn encrypt_and_decrypt_with_keyring(
example_data: &str,
kms_key_id: &str,
) -> Result<(), crate::BoxError> {
let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
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(),
),
]);
let mpl_config = MaterialProvidersConfig::builder().build()?;
let mpl = mpl_client::Client::from_conf(mpl_config)?;
let kms_keyring = mpl
.create_aws_kms_keyring()
.kms_key_id(kms_key_id)
.kms_client(kms_client)
.send()
.await?;
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");
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(kms_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!("KMS Keyring Example Completed Successfully");
Ok(())
}
#[tokio::test]
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, utils::TEST_DEFAULT_KMS_KEY_ID)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
pub async fn test_encrypt_and_decrypt_with_keyring_async() -> Result<(), crate::BoxError2> {
use crate::example_utils::utils;
let handle = tokio::spawn(async move {
encrypt_and_decrypt_with_keyring(utils::TEST_EXAMPLE_DATA, utils::TEST_DEFAULT_KMS_KEY_ID)
.await
});
assert!(handle.await.unwrap().is_ok());
Ok(())
}