DecryptFluentBuilder

Struct DecryptFluentBuilder 

Source
pub struct DecryptFluentBuilder { /* private fields */ }
Expand description

Fluent builder constructing a request to Decrypt.

Implementations§

Source§

impl DecryptFluentBuilder

Source

pub fn as_input(&self) -> &DecryptInputBuilder

Access the Decrypt as a reference.

Source

pub async fn send(self) -> Result<DecryptOutput, Error>

Sends the request and returns the response.

Examples found in repository?
examples/keyring/aws_kms_keyring_example.rs (line 105)
30pub async fn encrypt_and_decrypt_with_keyring(
31    example_data: &str,
32    kms_key_id: &str,
33) -> Result<(), crate::BoxError> {
34    // 1. Instantiate the encryption SDK client.
35    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
36    // which enforces that this client only encrypts using committing algorithm suites and enforces
37    // that this client will only decrypt encrypted messages that were created with a committing
38    // algorithm suite.
39    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
40    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
41
42    // 2. Create a KMS client.
43    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
44    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
45
46    // 3. Create encryption context.
47    // Remember that your encryption context is NOT SECRET.
48    // For more information, see
49    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
50    let encryption_context = HashMap::from([
51        ("encryption".to_string(), "context".to_string()),
52        ("is not".to_string(), "secret".to_string()),
53        ("but adds".to_string(), "useful metadata".to_string()),
54        (
55            "that can help you".to_string(),
56            "be confident that".to_string(),
57        ),
58        (
59            "the data you are handling".to_string(),
60            "is what you think it is".to_string(),
61        ),
62    ]);
63
64    // 4. Create a KMS keyring
65    let mpl_config = MaterialProvidersConfig::builder().build()?;
66    let mpl = mpl_client::Client::from_conf(mpl_config)?;
67
68    let kms_keyring = mpl
69        .create_aws_kms_keyring()
70        .kms_key_id(kms_key_id)
71        .kms_client(kms_client)
72        .send()
73        .await?;
74
75    // 5. Encrypt the data with the encryption_context
76    let plaintext = example_data.as_bytes();
77
78    let encryption_response = esdk_client
79        .encrypt()
80        .plaintext(plaintext)
81        .keyring(kms_keyring.clone())
82        .encryption_context(encryption_context.clone())
83        .send()
84        .await?;
85
86    let ciphertext = encryption_response
87        .ciphertext
88        .expect("Unable to unwrap ciphertext from encryption response");
89
90    // 6. Demonstrate that the ciphertext and plaintext are different.
91    // (This is an example for demonstration; you do not need to do this in your own code.)
92    assert_ne!(
93        ciphertext,
94        aws_smithy_types::Blob::new(plaintext),
95        "Ciphertext and plaintext data are the same. Invalid encryption"
96    );
97
98    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
99    let decryption_response = esdk_client
100        .decrypt()
101        .ciphertext(ciphertext)
102        .keyring(kms_keyring)
103        // Provide the encryption context that was supplied to the encrypt method
104        .encryption_context(encryption_context)
105        .send()
106        .await?;
107
108    let decrypted_plaintext = decryption_response
109        .plaintext
110        .expect("Unable to unwrap plaintext from decryption response");
111
112    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
113    // (This is an example for demonstration; you do not need to do this in your own code.)
114    assert_eq!(
115        decrypted_plaintext,
116        aws_smithy_types::Blob::new(plaintext),
117        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
118    );
119
120    println!("KMS Keyring Example Completed Successfully");
121
122    Ok(())
123}
More examples
Hide additional examples
examples/keyring/aws_kms_rsa_keyring_example.rs (line 109)
28pub async fn encrypt_and_decrypt_with_keyring(
29    example_data: &str,
30    kms_rsa_key_id: &str,
31    kms_rsa_public_key: &str,
32) -> Result<(), crate::BoxError> {
33    // 1. Instantiate the encryption SDK client.
34    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
35    // which enforces that this client only encrypts using committing algorithm suites and enforces
36    // that this client will only decrypt encrypted messages that were created with a committing
37    // algorithm suite.
38    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
39    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
40
41    // 2. Create a KMS client.
42    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
43    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
44
45    // 3. Create encryption context.
46    // Remember that your encryption context is NOT SECRET.
47    // For more information, see
48    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
49    let encryption_context = HashMap::from([
50        ("encryption".to_string(), "context".to_string()),
51        ("is not".to_string(), "secret".to_string()),
52        ("but adds".to_string(), "useful metadata".to_string()),
53        (
54            "that can help you".to_string(),
55            "be confident that".to_string(),
56        ),
57        (
58            "the data you are handling".to_string(),
59            "is what you think it is".to_string(),
60        ),
61    ]);
62
63    // 4. Create a KMS RSA keyring
64    let mpl_config = MaterialProvidersConfig::builder().build()?;
65    let mpl = mpl_client::Client::from_conf(mpl_config)?;
66
67    // For more information on the allowed encryption algorithms, please see
68    // https://docs.aws.amazon.com/kms/latest/developerguide/asymmetric-key-specs.html#key-spec-rsa
69    let kms_rsa_keyring = mpl
70        .create_aws_kms_rsa_keyring()
71        .kms_key_id(kms_rsa_key_id)
72        .public_key(aws_smithy_types::Blob::new(kms_rsa_public_key))
73        .encryption_algorithm(aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256)
74        .kms_client(kms_client)
75        .send()
76        .await?;
77
78    // 5. Encrypt the data with the encryption_context
79    let plaintext = example_data.as_bytes();
80
81    let encryption_response = esdk_client
82        .encrypt()
83        .plaintext(plaintext)
84        .keyring(kms_rsa_keyring.clone())
85        .encryption_context(encryption_context.clone())
86        .algorithm_suite_id(EsdkAlgorithmSuiteId::AlgAes256GcmHkdfSha512CommitKey)
87        .send()
88        .await?;
89
90    let ciphertext = encryption_response
91        .ciphertext
92        .expect("Unable to unwrap ciphertext from encryption response");
93
94    // 6. Demonstrate that the ciphertext and plaintext are different.
95    // (This is an example for demonstration; you do not need to do this in your own code.)
96    assert_ne!(
97        ciphertext,
98        aws_smithy_types::Blob::new(plaintext),
99        "Ciphertext and plaintext data are the same. Invalid encryption"
100    );
101
102    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
103    let decryption_response = esdk_client
104        .decrypt()
105        .ciphertext(ciphertext)
106        .keyring(kms_rsa_keyring)
107        // Provide the encryption context that was supplied to the encrypt method
108        .encryption_context(encryption_context)
109        .send()
110        .await?;
111
112    let decrypted_plaintext = decryption_response
113        .plaintext
114        .expect("Unable to unwrap plaintext from decryption response");
115
116    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
117    // (This is an example for demonstration; you do not need to do this in your own code.)
118    assert_eq!(
119        decrypted_plaintext,
120        aws_smithy_types::Blob::new(plaintext),
121        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
122    );
123
124    println!("KMS RSA Keyring Example Completed Successfully");
125
126    Ok(())
127}
examples/keyring/raw_aes_keyring_example.rs (line 116)
34pub async fn encrypt_and_decrypt_with_keyring(example_data: &str) -> Result<(), crate::BoxError> {
35    // 1. Instantiate the encryption SDK client.
36    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
37    // which enforces that this client only encrypts using committing algorithm suites and enforces
38    // that this client will only decrypt encrypted messages that were created with a committing
39    // algorithm suite.
40    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
41    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
42
43    // 2. The key namespace and key name are defined by you.
44    // and are used by the Raw AES keyring to determine
45    // whether it should attempt to decrypt an encrypted data key.
46    // For more information, see
47    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html
48    let key_namespace: &str = "my-key-namespace";
49    let key_name: &str = "my-aes-key-name";
50
51    // 3. Create encryption context.
52    // Remember that your encryption context is NOT SECRET.
53    // For more information, see
54    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
55    let encryption_context = HashMap::from([
56        ("encryption".to_string(), "context".to_string()),
57        ("is not".to_string(), "secret".to_string()),
58        ("but adds".to_string(), "useful metadata".to_string()),
59        (
60            "that can help you".to_string(),
61            "be confident that".to_string(),
62        ),
63        (
64            "the data you are handling".to_string(),
65            "is what you think it is".to_string(),
66        ),
67    ]);
68
69    // 4. Generate a 256-bit AES key to use with your keyring.
70    // In practice, you should get this key from a secure key management system such as an HSM.
71    let aes_key_bytes = generate_aes_key_bytes();
72
73    // 5. Create a Raw AES Keyring
74    let mpl_config = MaterialProvidersConfig::builder().build()?;
75    let mpl = mpl_client::Client::from_conf(mpl_config)?;
76
77    let raw_aes_keyring = mpl
78        .create_raw_aes_keyring()
79        .key_name(key_name)
80        .key_namespace(key_namespace)
81        .wrapping_key(aes_key_bytes)
82        .wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
83        .send()
84        .await?;
85
86    // 6. Encrypt the data with the encryption_context
87    let plaintext = example_data.as_bytes();
88
89    let encryption_response = esdk_client
90        .encrypt()
91        .plaintext(plaintext)
92        .keyring(raw_aes_keyring.clone())
93        .encryption_context(encryption_context.clone())
94        .send()
95        .await?;
96
97    let ciphertext = encryption_response
98        .ciphertext
99        .expect("Unable to unwrap ciphertext from encryption response");
100
101    // 7. Demonstrate that the ciphertext and plaintext are different.
102    // (This is an example for demonstration; you do not need to do this in your own code.)
103    assert_ne!(
104        ciphertext,
105        aws_smithy_types::Blob::new(plaintext),
106        "Ciphertext and plaintext data are the same. Invalid encryption"
107    );
108
109    // 8. Decrypt your encrypted data using the same keyring you used on encrypt.
110    let decryption_response = esdk_client
111        .decrypt()
112        .ciphertext(ciphertext)
113        .keyring(raw_aes_keyring)
114        // Provide the encryption context that was supplied to the encrypt method
115        .encryption_context(encryption_context)
116        .send()
117        .await?;
118
119    let decrypted_plaintext = decryption_response
120        .plaintext
121        .expect("Unable to unwrap plaintext from decryption response");
122
123    // 9. Demonstrate that the decrypted plaintext is identical to the original plaintext.
124    // (This is an example for demonstration; you do not need to do this in your own code.)
125    assert_eq!(
126        decrypted_plaintext,
127        aws_smithy_types::Blob::new(plaintext),
128        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
129    );
130
131    println!("Raw AES Keyring Example Completed Successfully");
132
133    Ok(())
134}
examples/set_encryption_algorithm_suite_example.rs (line 137)
51pub async fn encrypt_and_decrypt_with_keyring(example_data: &str) -> Result<(), crate::BoxError> {
52    // 1. Instantiate the encryption SDK client.
53    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
54    // which enforces that this client only encrypts using committing algorithm suites and enforces
55    // that this client will only decrypt encrypted messages that were created with a committing
56    // algorithm suite.
57    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
58    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
59
60    // 2. The key namespace and key name are defined by you.
61    // and are used by the Raw AES keyring to determine
62    // whether it should attempt to decrypt an encrypted data key.
63    // For more information, see
64    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html
65    let key_namespace: &str = "my-key-namespace";
66    let key_name: &str = "my-aes-key-name";
67
68    // 3. Create encryption context.
69    // Remember that your encryption context is NOT SECRET.
70    // For more information, see
71    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
72    let encryption_context = HashMap::from([
73        ("encryption".to_string(), "context".to_string()),
74        ("is not".to_string(), "secret".to_string()),
75        ("but adds".to_string(), "useful metadata".to_string()),
76        (
77            "that can help you".to_string(),
78            "be confident that".to_string(),
79        ),
80        (
81            "the data you are handling".to_string(),
82            "is what you think it is".to_string(),
83        ),
84    ]);
85
86    // 4. Generate a 256-bit AES key to use with your keyring.
87    // In practice, you should get this key from a secure key management system such as an HSM.
88    let aes_key_bytes = generate_aes_key_bytes();
89
90    // 5. Create a Raw AES Keyring
91    let mpl_config = MaterialProvidersConfig::builder().build()?;
92    let mpl = mpl_client::Client::from_conf(mpl_config)?;
93
94    // The wrapping algorithm here is NOT the algorithm suite we set in this example.
95    let raw_aes_keyring = mpl
96        .create_raw_aes_keyring()
97        .key_name(key_name)
98        .key_namespace(key_namespace)
99        .wrapping_key(aes_key_bytes)
100        .wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
101        .send()
102        .await?;
103
104    // 6. Encrypt the data with the encryption_context
105    let plaintext = example_data.as_bytes();
106
107    // This is the important step in this example where we specify the algorithm suite
108    // you want to use for encrypting your data
109    let encryption_response = esdk_client
110        .encrypt()
111        .plaintext(plaintext)
112        .keyring(raw_aes_keyring.clone())
113        .encryption_context(encryption_context.clone())
114        .algorithm_suite_id(AlgAes256GcmHkdfSha512CommitKey)
115        .send()
116        .await?;
117
118    let ciphertext = encryption_response
119        .ciphertext
120        .expect("Unable to unwrap ciphertext from encryption response");
121
122    // 7. Demonstrate that the ciphertext and plaintext are different.
123    // (This is an example for demonstration; you do not need to do this in your own code.)
124    assert_ne!(
125        ciphertext,
126        aws_smithy_types::Blob::new(plaintext),
127        "Ciphertext and plaintext data are the same. Invalid encryption"
128    );
129
130    // 8. Decrypt your encrypted data using the same keyring you used on encrypt.
131    let decryption_response = esdk_client
132        .decrypt()
133        .ciphertext(ciphertext)
134        .keyring(raw_aes_keyring)
135        // Provide the encryption context that was supplied to the encrypt method
136        .encryption_context(encryption_context)
137        .send()
138        .await?;
139
140    let decrypted_plaintext = decryption_response
141        .plaintext
142        .expect("Unable to unwrap plaintext from decryption response");
143
144    // 9. Demonstrate that the decrypted plaintext is identical to the original plaintext.
145    // (This is an example for demonstration; you do not need to do this in your own code.)
146    assert_eq!(
147        decrypted_plaintext,
148        aws_smithy_types::Blob::new(plaintext),
149        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
150    );
151
152    println!("Set Encryption Algorithm Suite Example Completed Successfully");
153
154    Ok(())
155}
examples/set_commitment_policy_example.rs (line 124)
34pub async fn encrypt_and_decrypt_with_keyring(
35    example_data: &str,
36    kms_key_id: &str,
37) -> Result<(), crate::BoxError> {
38    // 1. Instantiate the encryption SDK client.
39    // This example builds the client with the ForbidEncryptAllowDecrypt commitment policy,
40    // which enforces that this client cannot encrypt with key commitment
41    // and it can decrypt ciphertexts encrypted with or without key commitment.
42    // The default commitment policy if you were to build the client like in
43    // the `keyring/aws_kms_keyring_example.rs` is RequireEncryptRequireDecrypt.
44    // We recommend that AWS Encryption SDK users use the default commitment policy
45    // (RequireEncryptRequireDecrypt) whenever possible.
46    let esdk_config = AwsEncryptionSdkConfig::builder()
47        .commitment_policy(ForbidEncryptAllowDecrypt)
48        .build()?;
49    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
50
51    // 2. Create a KMS client.
52    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
53    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
54
55    // 3. Create encryption context.
56    // Remember that your encryption context is NOT SECRET.
57    // For more information, see
58    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
59    let encryption_context = HashMap::from([
60        ("encryption".to_string(), "context".to_string()),
61        ("is not".to_string(), "secret".to_string()),
62        ("but adds".to_string(), "useful metadata".to_string()),
63        (
64            "that can help you".to_string(),
65            "be confident that".to_string(),
66        ),
67        (
68            "the data you are handling".to_string(),
69            "is what you think it is".to_string(),
70        ),
71    ]);
72
73    // 4. Create a KMS keyring
74    let mpl_config = MaterialProvidersConfig::builder().build()?;
75    let mpl = mpl_client::Client::from_conf(mpl_config)?;
76
77    let kms_keyring = mpl
78        .create_aws_kms_keyring()
79        .kms_key_id(kms_key_id)
80        .kms_client(kms_client)
81        .send()
82        .await?;
83
84    // 5. Encrypt the data with the encryption_context. Make sure you use a non-committing algorithm
85    // with the commitment policy ForbidEncryptAllowDecrypt. Otherwise esdk_client.encrypt() will throw
86    // Error: AwsCryptographicMaterialProvidersError
87    //   {
88    //     error: InvalidAlgorithmSuiteInfoOnEncrypt
89    //     {
90    //       message: "Configuration conflict. Commitment policy requires only non-committing algorithm suites"
91    //     }
92    //   }
93    // By default for ForbidEncryptAllowDecrypt, the algorithm used is
94    // AlgAes256GcmIv12Tag16HkdfSha384EcdsaP384 which is a non-committing algorithm.
95    let plaintext = example_data.as_bytes();
96
97    let encryption_response = esdk_client
98        .encrypt()
99        .plaintext(plaintext)
100        .keyring(kms_keyring.clone())
101        .encryption_context(encryption_context.clone())
102        .send()
103        .await?;
104
105    let ciphertext = encryption_response
106        .ciphertext
107        .expect("Unable to unwrap ciphertext from encryption response");
108
109    // 6. Demonstrate that the ciphertext and plaintext are different.
110    // (This is an example for demonstration; you do not need to do this in your own code.)
111    assert_ne!(
112        ciphertext,
113        aws_smithy_types::Blob::new(plaintext),
114        "Ciphertext and plaintext data are the same. Invalid encryption"
115    );
116
117    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
118    let decryption_response = esdk_client
119        .decrypt()
120        .ciphertext(ciphertext)
121        .keyring(kms_keyring)
122        // Provide the encryption context that was supplied to the encrypt method
123        .encryption_context(encryption_context)
124        .send()
125        .await?;
126
127    let decrypted_plaintext = decryption_response
128        .plaintext
129        .expect("Unable to unwrap plaintext from decryption response");
130
131    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
132    // (This is an example for demonstration; you do not need to do this in your own code.)
133    assert_eq!(
134        decrypted_plaintext,
135        aws_smithy_types::Blob::new(plaintext),
136        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
137    );
138
139    println!("Set Commitment Policy Example Completed Successfully");
140
141    Ok(())
142}
examples/keyring/ecdh/public_key_discovery_raw_ecdh_keyring_example.rs (line 157)
66pub async fn decrypt_with_keyring(
67    example_data: &str,
68    ecdh_curve_spec: EcdhCurveSpec,
69) -> Result<(), crate::BoxError> {
70    // 1. Instantiate the encryption SDK client.
71    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
72    // which enforces that this client only encrypts using committing algorithm suites and enforces
73    // that this client will only decrypt encrypted messages that were created with a committing
74    // algorithm suite.
75    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
76    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
77
78    let mpl_config = MaterialProvidersConfig::builder().build()?;
79    let mpl = mpl_client::Client::from_conf(mpl_config)?;
80
81    // 2. Create encryption context.
82    // Remember that your encryption context is NOT SECRET.
83    // For more information, see
84    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
85    let encryption_context = HashMap::from([
86        ("encryption".to_string(), "context".to_string()),
87        ("is not".to_string(), "secret".to_string()),
88        ("but adds".to_string(), "useful metadata".to_string()),
89        (
90            "that can help you".to_string(),
91            "be confident that".to_string(),
92        ),
93        (
94            "the data you are handling".to_string(),
95            "is what you think it is".to_string(),
96        ),
97    ]);
98
99    // 3. You may provide your own ECC keys in the files located at
100    // - EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT
101
102    // If you do not provide these files, running this example through this
103    // class' main method will generate three files required for all raw ECDH examples
104    // EXAMPLE_ECC_PRIVATE_KEY_FILENAME_SENDER, EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT
105    // and EXAMPLE_ECC_PUBLIC_KEY_FILENAME_RECIPIENT for you.
106
107    // Do not use these files for any other purpose.
108    if should_generate_new_ecc_key_pair_discovery_raw_ecdh()? {
109        write_raw_ecdh_ecc_keys(ecdh_curve_spec)?;
110    }
111
112    // 4. Load keys from UTF-8 encoded PEM files.
113    let mut file = File::open(Path::new(EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT))?;
114    let mut private_key_recipient_utf8_bytes = Vec::new();
115    file.read_to_end(&mut private_key_recipient_utf8_bytes)?;
116
117    // Generate the ciphertext
118    let ciphertext = get_ciphertext(
119        example_data,
120        ecdh_curve_spec,
121        encryption_context.clone(),
122        esdk_client.clone(),
123        mpl.clone(),
124    )
125    .await?;
126
127    // 5. Create the PublicKeyDiscoveryInput
128    let discovery_raw_ecdh_static_configuration_input = PublicKeyDiscoveryInput::builder()
129        // Must be a UTF8 PEM-encoded private key
130        .recipient_static_private_key(private_key_recipient_utf8_bytes)
131        .build()?;
132
133    let discovery_raw_ecdh_static_configuration = RawEcdhStaticConfigurations::PublicKeyDiscovery(
134        discovery_raw_ecdh_static_configuration_input,
135    );
136
137    // 6. Create the Public Key Discovery Raw ECDH keyring.
138
139    // Create the keyring.
140    // This keyring uses a discovery configuration. This configuration will check on decrypt
141    // if it is meant to decrypt the message by checking if the configured public key is stored on the message.
142    // The discovery configuration can only decrypt messages and CANNOT encrypt messages.
143    let discovery_raw_ecdh_keyring = mpl
144        .create_raw_ecdh_keyring()
145        .curve_spec(ecdh_curve_spec)
146        .key_agreement_scheme(discovery_raw_ecdh_static_configuration)
147        .send()
148        .await?;
149
150    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
151    let decryption_response = esdk_client
152        .decrypt()
153        .ciphertext(ciphertext)
154        .keyring(discovery_raw_ecdh_keyring)
155        // Provide the encryption context that was supplied to the encrypt method
156        .encryption_context(encryption_context)
157        .send()
158        .await?;
159
160    let decrypted_plaintext = decryption_response
161        .plaintext
162        .expect("Unable to unwrap plaintext from decryption response");
163
164    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
165    // (This is an example for demonstration; you do not need to do this in your own code.)
166    let plaintext = example_data.as_bytes();
167
168    assert_eq!(
169        decrypted_plaintext,
170        aws_smithy_types::Blob::new(plaintext),
171        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
172    );
173
174    println!("Public Key Discovery Raw ECDH Keyring Example Completed Successfully");
175
176    Ok(())
177}
Source

pub fn ciphertext(self, input: impl Into<Blob>) -> Self

Examples found in repository?
examples/keyring/aws_kms_keyring_example.rs (line 101)
30pub async fn encrypt_and_decrypt_with_keyring(
31    example_data: &str,
32    kms_key_id: &str,
33) -> Result<(), crate::BoxError> {
34    // 1. Instantiate the encryption SDK client.
35    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
36    // which enforces that this client only encrypts using committing algorithm suites and enforces
37    // that this client will only decrypt encrypted messages that were created with a committing
38    // algorithm suite.
39    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
40    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
41
42    // 2. Create a KMS client.
43    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
44    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
45
46    // 3. Create encryption context.
47    // Remember that your encryption context is NOT SECRET.
48    // For more information, see
49    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
50    let encryption_context = HashMap::from([
51        ("encryption".to_string(), "context".to_string()),
52        ("is not".to_string(), "secret".to_string()),
53        ("but adds".to_string(), "useful metadata".to_string()),
54        (
55            "that can help you".to_string(),
56            "be confident that".to_string(),
57        ),
58        (
59            "the data you are handling".to_string(),
60            "is what you think it is".to_string(),
61        ),
62    ]);
63
64    // 4. Create a KMS keyring
65    let mpl_config = MaterialProvidersConfig::builder().build()?;
66    let mpl = mpl_client::Client::from_conf(mpl_config)?;
67
68    let kms_keyring = mpl
69        .create_aws_kms_keyring()
70        .kms_key_id(kms_key_id)
71        .kms_client(kms_client)
72        .send()
73        .await?;
74
75    // 5. Encrypt the data with the encryption_context
76    let plaintext = example_data.as_bytes();
77
78    let encryption_response = esdk_client
79        .encrypt()
80        .plaintext(plaintext)
81        .keyring(kms_keyring.clone())
82        .encryption_context(encryption_context.clone())
83        .send()
84        .await?;
85
86    let ciphertext = encryption_response
87        .ciphertext
88        .expect("Unable to unwrap ciphertext from encryption response");
89
90    // 6. Demonstrate that the ciphertext and plaintext are different.
91    // (This is an example for demonstration; you do not need to do this in your own code.)
92    assert_ne!(
93        ciphertext,
94        aws_smithy_types::Blob::new(plaintext),
95        "Ciphertext and plaintext data are the same. Invalid encryption"
96    );
97
98    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
99    let decryption_response = esdk_client
100        .decrypt()
101        .ciphertext(ciphertext)
102        .keyring(kms_keyring)
103        // Provide the encryption context that was supplied to the encrypt method
104        .encryption_context(encryption_context)
105        .send()
106        .await?;
107
108    let decrypted_plaintext = decryption_response
109        .plaintext
110        .expect("Unable to unwrap plaintext from decryption response");
111
112    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
113    // (This is an example for demonstration; you do not need to do this in your own code.)
114    assert_eq!(
115        decrypted_plaintext,
116        aws_smithy_types::Blob::new(plaintext),
117        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
118    );
119
120    println!("KMS Keyring Example Completed Successfully");
121
122    Ok(())
123}
More examples
Hide additional examples
examples/keyring/aws_kms_rsa_keyring_example.rs (line 105)
28pub async fn encrypt_and_decrypt_with_keyring(
29    example_data: &str,
30    kms_rsa_key_id: &str,
31    kms_rsa_public_key: &str,
32) -> Result<(), crate::BoxError> {
33    // 1. Instantiate the encryption SDK client.
34    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
35    // which enforces that this client only encrypts using committing algorithm suites and enforces
36    // that this client will only decrypt encrypted messages that were created with a committing
37    // algorithm suite.
38    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
39    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
40
41    // 2. Create a KMS client.
42    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
43    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
44
45    // 3. Create encryption context.
46    // Remember that your encryption context is NOT SECRET.
47    // For more information, see
48    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
49    let encryption_context = HashMap::from([
50        ("encryption".to_string(), "context".to_string()),
51        ("is not".to_string(), "secret".to_string()),
52        ("but adds".to_string(), "useful metadata".to_string()),
53        (
54            "that can help you".to_string(),
55            "be confident that".to_string(),
56        ),
57        (
58            "the data you are handling".to_string(),
59            "is what you think it is".to_string(),
60        ),
61    ]);
62
63    // 4. Create a KMS RSA keyring
64    let mpl_config = MaterialProvidersConfig::builder().build()?;
65    let mpl = mpl_client::Client::from_conf(mpl_config)?;
66
67    // For more information on the allowed encryption algorithms, please see
68    // https://docs.aws.amazon.com/kms/latest/developerguide/asymmetric-key-specs.html#key-spec-rsa
69    let kms_rsa_keyring = mpl
70        .create_aws_kms_rsa_keyring()
71        .kms_key_id(kms_rsa_key_id)
72        .public_key(aws_smithy_types::Blob::new(kms_rsa_public_key))
73        .encryption_algorithm(aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256)
74        .kms_client(kms_client)
75        .send()
76        .await?;
77
78    // 5. Encrypt the data with the encryption_context
79    let plaintext = example_data.as_bytes();
80
81    let encryption_response = esdk_client
82        .encrypt()
83        .plaintext(plaintext)
84        .keyring(kms_rsa_keyring.clone())
85        .encryption_context(encryption_context.clone())
86        .algorithm_suite_id(EsdkAlgorithmSuiteId::AlgAes256GcmHkdfSha512CommitKey)
87        .send()
88        .await?;
89
90    let ciphertext = encryption_response
91        .ciphertext
92        .expect("Unable to unwrap ciphertext from encryption response");
93
94    // 6. Demonstrate that the ciphertext and plaintext are different.
95    // (This is an example for demonstration; you do not need to do this in your own code.)
96    assert_ne!(
97        ciphertext,
98        aws_smithy_types::Blob::new(plaintext),
99        "Ciphertext and plaintext data are the same. Invalid encryption"
100    );
101
102    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
103    let decryption_response = esdk_client
104        .decrypt()
105        .ciphertext(ciphertext)
106        .keyring(kms_rsa_keyring)
107        // Provide the encryption context that was supplied to the encrypt method
108        .encryption_context(encryption_context)
109        .send()
110        .await?;
111
112    let decrypted_plaintext = decryption_response
113        .plaintext
114        .expect("Unable to unwrap plaintext from decryption response");
115
116    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
117    // (This is an example for demonstration; you do not need to do this in your own code.)
118    assert_eq!(
119        decrypted_plaintext,
120        aws_smithy_types::Blob::new(plaintext),
121        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
122    );
123
124    println!("KMS RSA Keyring Example Completed Successfully");
125
126    Ok(())
127}
examples/keyring/raw_aes_keyring_example.rs (line 112)
34pub async fn encrypt_and_decrypt_with_keyring(example_data: &str) -> Result<(), crate::BoxError> {
35    // 1. Instantiate the encryption SDK client.
36    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
37    // which enforces that this client only encrypts using committing algorithm suites and enforces
38    // that this client will only decrypt encrypted messages that were created with a committing
39    // algorithm suite.
40    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
41    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
42
43    // 2. The key namespace and key name are defined by you.
44    // and are used by the Raw AES keyring to determine
45    // whether it should attempt to decrypt an encrypted data key.
46    // For more information, see
47    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html
48    let key_namespace: &str = "my-key-namespace";
49    let key_name: &str = "my-aes-key-name";
50
51    // 3. Create encryption context.
52    // Remember that your encryption context is NOT SECRET.
53    // For more information, see
54    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
55    let encryption_context = HashMap::from([
56        ("encryption".to_string(), "context".to_string()),
57        ("is not".to_string(), "secret".to_string()),
58        ("but adds".to_string(), "useful metadata".to_string()),
59        (
60            "that can help you".to_string(),
61            "be confident that".to_string(),
62        ),
63        (
64            "the data you are handling".to_string(),
65            "is what you think it is".to_string(),
66        ),
67    ]);
68
69    // 4. Generate a 256-bit AES key to use with your keyring.
70    // In practice, you should get this key from a secure key management system such as an HSM.
71    let aes_key_bytes = generate_aes_key_bytes();
72
73    // 5. Create a Raw AES Keyring
74    let mpl_config = MaterialProvidersConfig::builder().build()?;
75    let mpl = mpl_client::Client::from_conf(mpl_config)?;
76
77    let raw_aes_keyring = mpl
78        .create_raw_aes_keyring()
79        .key_name(key_name)
80        .key_namespace(key_namespace)
81        .wrapping_key(aes_key_bytes)
82        .wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
83        .send()
84        .await?;
85
86    // 6. Encrypt the data with the encryption_context
87    let plaintext = example_data.as_bytes();
88
89    let encryption_response = esdk_client
90        .encrypt()
91        .plaintext(plaintext)
92        .keyring(raw_aes_keyring.clone())
93        .encryption_context(encryption_context.clone())
94        .send()
95        .await?;
96
97    let ciphertext = encryption_response
98        .ciphertext
99        .expect("Unable to unwrap ciphertext from encryption response");
100
101    // 7. Demonstrate that the ciphertext and plaintext are different.
102    // (This is an example for demonstration; you do not need to do this in your own code.)
103    assert_ne!(
104        ciphertext,
105        aws_smithy_types::Blob::new(plaintext),
106        "Ciphertext and plaintext data are the same. Invalid encryption"
107    );
108
109    // 8. Decrypt your encrypted data using the same keyring you used on encrypt.
110    let decryption_response = esdk_client
111        .decrypt()
112        .ciphertext(ciphertext)
113        .keyring(raw_aes_keyring)
114        // Provide the encryption context that was supplied to the encrypt method
115        .encryption_context(encryption_context)
116        .send()
117        .await?;
118
119    let decrypted_plaintext = decryption_response
120        .plaintext
121        .expect("Unable to unwrap plaintext from decryption response");
122
123    // 9. Demonstrate that the decrypted plaintext is identical to the original plaintext.
124    // (This is an example for demonstration; you do not need to do this in your own code.)
125    assert_eq!(
126        decrypted_plaintext,
127        aws_smithy_types::Blob::new(plaintext),
128        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
129    );
130
131    println!("Raw AES Keyring Example Completed Successfully");
132
133    Ok(())
134}
examples/set_encryption_algorithm_suite_example.rs (line 133)
51pub async fn encrypt_and_decrypt_with_keyring(example_data: &str) -> Result<(), crate::BoxError> {
52    // 1. Instantiate the encryption SDK client.
53    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
54    // which enforces that this client only encrypts using committing algorithm suites and enforces
55    // that this client will only decrypt encrypted messages that were created with a committing
56    // algorithm suite.
57    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
58    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
59
60    // 2. The key namespace and key name are defined by you.
61    // and are used by the Raw AES keyring to determine
62    // whether it should attempt to decrypt an encrypted data key.
63    // For more information, see
64    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html
65    let key_namespace: &str = "my-key-namespace";
66    let key_name: &str = "my-aes-key-name";
67
68    // 3. Create encryption context.
69    // Remember that your encryption context is NOT SECRET.
70    // For more information, see
71    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
72    let encryption_context = HashMap::from([
73        ("encryption".to_string(), "context".to_string()),
74        ("is not".to_string(), "secret".to_string()),
75        ("but adds".to_string(), "useful metadata".to_string()),
76        (
77            "that can help you".to_string(),
78            "be confident that".to_string(),
79        ),
80        (
81            "the data you are handling".to_string(),
82            "is what you think it is".to_string(),
83        ),
84    ]);
85
86    // 4. Generate a 256-bit AES key to use with your keyring.
87    // In practice, you should get this key from a secure key management system such as an HSM.
88    let aes_key_bytes = generate_aes_key_bytes();
89
90    // 5. Create a Raw AES Keyring
91    let mpl_config = MaterialProvidersConfig::builder().build()?;
92    let mpl = mpl_client::Client::from_conf(mpl_config)?;
93
94    // The wrapping algorithm here is NOT the algorithm suite we set in this example.
95    let raw_aes_keyring = mpl
96        .create_raw_aes_keyring()
97        .key_name(key_name)
98        .key_namespace(key_namespace)
99        .wrapping_key(aes_key_bytes)
100        .wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
101        .send()
102        .await?;
103
104    // 6. Encrypt the data with the encryption_context
105    let plaintext = example_data.as_bytes();
106
107    // This is the important step in this example where we specify the algorithm suite
108    // you want to use for encrypting your data
109    let encryption_response = esdk_client
110        .encrypt()
111        .plaintext(plaintext)
112        .keyring(raw_aes_keyring.clone())
113        .encryption_context(encryption_context.clone())
114        .algorithm_suite_id(AlgAes256GcmHkdfSha512CommitKey)
115        .send()
116        .await?;
117
118    let ciphertext = encryption_response
119        .ciphertext
120        .expect("Unable to unwrap ciphertext from encryption response");
121
122    // 7. Demonstrate that the ciphertext and plaintext are different.
123    // (This is an example for demonstration; you do not need to do this in your own code.)
124    assert_ne!(
125        ciphertext,
126        aws_smithy_types::Blob::new(plaintext),
127        "Ciphertext and plaintext data are the same. Invalid encryption"
128    );
129
130    // 8. Decrypt your encrypted data using the same keyring you used on encrypt.
131    let decryption_response = esdk_client
132        .decrypt()
133        .ciphertext(ciphertext)
134        .keyring(raw_aes_keyring)
135        // Provide the encryption context that was supplied to the encrypt method
136        .encryption_context(encryption_context)
137        .send()
138        .await?;
139
140    let decrypted_plaintext = decryption_response
141        .plaintext
142        .expect("Unable to unwrap plaintext from decryption response");
143
144    // 9. Demonstrate that the decrypted plaintext is identical to the original plaintext.
145    // (This is an example for demonstration; you do not need to do this in your own code.)
146    assert_eq!(
147        decrypted_plaintext,
148        aws_smithy_types::Blob::new(plaintext),
149        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
150    );
151
152    println!("Set Encryption Algorithm Suite Example Completed Successfully");
153
154    Ok(())
155}
examples/set_commitment_policy_example.rs (line 120)
34pub async fn encrypt_and_decrypt_with_keyring(
35    example_data: &str,
36    kms_key_id: &str,
37) -> Result<(), crate::BoxError> {
38    // 1. Instantiate the encryption SDK client.
39    // This example builds the client with the ForbidEncryptAllowDecrypt commitment policy,
40    // which enforces that this client cannot encrypt with key commitment
41    // and it can decrypt ciphertexts encrypted with or without key commitment.
42    // The default commitment policy if you were to build the client like in
43    // the `keyring/aws_kms_keyring_example.rs` is RequireEncryptRequireDecrypt.
44    // We recommend that AWS Encryption SDK users use the default commitment policy
45    // (RequireEncryptRequireDecrypt) whenever possible.
46    let esdk_config = AwsEncryptionSdkConfig::builder()
47        .commitment_policy(ForbidEncryptAllowDecrypt)
48        .build()?;
49    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
50
51    // 2. Create a KMS client.
52    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
53    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
54
55    // 3. Create encryption context.
56    // Remember that your encryption context is NOT SECRET.
57    // For more information, see
58    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
59    let encryption_context = HashMap::from([
60        ("encryption".to_string(), "context".to_string()),
61        ("is not".to_string(), "secret".to_string()),
62        ("but adds".to_string(), "useful metadata".to_string()),
63        (
64            "that can help you".to_string(),
65            "be confident that".to_string(),
66        ),
67        (
68            "the data you are handling".to_string(),
69            "is what you think it is".to_string(),
70        ),
71    ]);
72
73    // 4. Create a KMS keyring
74    let mpl_config = MaterialProvidersConfig::builder().build()?;
75    let mpl = mpl_client::Client::from_conf(mpl_config)?;
76
77    let kms_keyring = mpl
78        .create_aws_kms_keyring()
79        .kms_key_id(kms_key_id)
80        .kms_client(kms_client)
81        .send()
82        .await?;
83
84    // 5. Encrypt the data with the encryption_context. Make sure you use a non-committing algorithm
85    // with the commitment policy ForbidEncryptAllowDecrypt. Otherwise esdk_client.encrypt() will throw
86    // Error: AwsCryptographicMaterialProvidersError
87    //   {
88    //     error: InvalidAlgorithmSuiteInfoOnEncrypt
89    //     {
90    //       message: "Configuration conflict. Commitment policy requires only non-committing algorithm suites"
91    //     }
92    //   }
93    // By default for ForbidEncryptAllowDecrypt, the algorithm used is
94    // AlgAes256GcmIv12Tag16HkdfSha384EcdsaP384 which is a non-committing algorithm.
95    let plaintext = example_data.as_bytes();
96
97    let encryption_response = esdk_client
98        .encrypt()
99        .plaintext(plaintext)
100        .keyring(kms_keyring.clone())
101        .encryption_context(encryption_context.clone())
102        .send()
103        .await?;
104
105    let ciphertext = encryption_response
106        .ciphertext
107        .expect("Unable to unwrap ciphertext from encryption response");
108
109    // 6. Demonstrate that the ciphertext and plaintext are different.
110    // (This is an example for demonstration; you do not need to do this in your own code.)
111    assert_ne!(
112        ciphertext,
113        aws_smithy_types::Blob::new(plaintext),
114        "Ciphertext and plaintext data are the same. Invalid encryption"
115    );
116
117    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
118    let decryption_response = esdk_client
119        .decrypt()
120        .ciphertext(ciphertext)
121        .keyring(kms_keyring)
122        // Provide the encryption context that was supplied to the encrypt method
123        .encryption_context(encryption_context)
124        .send()
125        .await?;
126
127    let decrypted_plaintext = decryption_response
128        .plaintext
129        .expect("Unable to unwrap plaintext from decryption response");
130
131    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
132    // (This is an example for demonstration; you do not need to do this in your own code.)
133    assert_eq!(
134        decrypted_plaintext,
135        aws_smithy_types::Blob::new(plaintext),
136        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
137    );
138
139    println!("Set Commitment Policy Example Completed Successfully");
140
141    Ok(())
142}
examples/keyring/ecdh/public_key_discovery_raw_ecdh_keyring_example.rs (line 153)
66pub async fn decrypt_with_keyring(
67    example_data: &str,
68    ecdh_curve_spec: EcdhCurveSpec,
69) -> Result<(), crate::BoxError> {
70    // 1. Instantiate the encryption SDK client.
71    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
72    // which enforces that this client only encrypts using committing algorithm suites and enforces
73    // that this client will only decrypt encrypted messages that were created with a committing
74    // algorithm suite.
75    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
76    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
77
78    let mpl_config = MaterialProvidersConfig::builder().build()?;
79    let mpl = mpl_client::Client::from_conf(mpl_config)?;
80
81    // 2. Create encryption context.
82    // Remember that your encryption context is NOT SECRET.
83    // For more information, see
84    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
85    let encryption_context = HashMap::from([
86        ("encryption".to_string(), "context".to_string()),
87        ("is not".to_string(), "secret".to_string()),
88        ("but adds".to_string(), "useful metadata".to_string()),
89        (
90            "that can help you".to_string(),
91            "be confident that".to_string(),
92        ),
93        (
94            "the data you are handling".to_string(),
95            "is what you think it is".to_string(),
96        ),
97    ]);
98
99    // 3. You may provide your own ECC keys in the files located at
100    // - EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT
101
102    // If you do not provide these files, running this example through this
103    // class' main method will generate three files required for all raw ECDH examples
104    // EXAMPLE_ECC_PRIVATE_KEY_FILENAME_SENDER, EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT
105    // and EXAMPLE_ECC_PUBLIC_KEY_FILENAME_RECIPIENT for you.
106
107    // Do not use these files for any other purpose.
108    if should_generate_new_ecc_key_pair_discovery_raw_ecdh()? {
109        write_raw_ecdh_ecc_keys(ecdh_curve_spec)?;
110    }
111
112    // 4. Load keys from UTF-8 encoded PEM files.
113    let mut file = File::open(Path::new(EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT))?;
114    let mut private_key_recipient_utf8_bytes = Vec::new();
115    file.read_to_end(&mut private_key_recipient_utf8_bytes)?;
116
117    // Generate the ciphertext
118    let ciphertext = get_ciphertext(
119        example_data,
120        ecdh_curve_spec,
121        encryption_context.clone(),
122        esdk_client.clone(),
123        mpl.clone(),
124    )
125    .await?;
126
127    // 5. Create the PublicKeyDiscoveryInput
128    let discovery_raw_ecdh_static_configuration_input = PublicKeyDiscoveryInput::builder()
129        // Must be a UTF8 PEM-encoded private key
130        .recipient_static_private_key(private_key_recipient_utf8_bytes)
131        .build()?;
132
133    let discovery_raw_ecdh_static_configuration = RawEcdhStaticConfigurations::PublicKeyDiscovery(
134        discovery_raw_ecdh_static_configuration_input,
135    );
136
137    // 6. Create the Public Key Discovery Raw ECDH keyring.
138
139    // Create the keyring.
140    // This keyring uses a discovery configuration. This configuration will check on decrypt
141    // if it is meant to decrypt the message by checking if the configured public key is stored on the message.
142    // The discovery configuration can only decrypt messages and CANNOT encrypt messages.
143    let discovery_raw_ecdh_keyring = mpl
144        .create_raw_ecdh_keyring()
145        .curve_spec(ecdh_curve_spec)
146        .key_agreement_scheme(discovery_raw_ecdh_static_configuration)
147        .send()
148        .await?;
149
150    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
151    let decryption_response = esdk_client
152        .decrypt()
153        .ciphertext(ciphertext)
154        .keyring(discovery_raw_ecdh_keyring)
155        // Provide the encryption context that was supplied to the encrypt method
156        .encryption_context(encryption_context)
157        .send()
158        .await?;
159
160    let decrypted_plaintext = decryption_response
161        .plaintext
162        .expect("Unable to unwrap plaintext from decryption response");
163
164    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
165    // (This is an example for demonstration; you do not need to do this in your own code.)
166    let plaintext = example_data.as_bytes();
167
168    assert_eq!(
169        decrypted_plaintext,
170        aws_smithy_types::Blob::new(plaintext),
171        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
172    );
173
174    println!("Public Key Discovery Raw ECDH Keyring Example Completed Successfully");
175
176    Ok(())
177}
Source

pub fn set_ciphertext(self, input: Option<Blob>) -> Self

Source

pub fn get_ciphertext(&self) -> &Option<Blob>

Source

pub fn encryption_context( self, input: impl Into<HashMap<String, String>>, ) -> Self

Examples found in repository?
examples/keyring/aws_kms_keyring_example.rs (line 104)
30pub async fn encrypt_and_decrypt_with_keyring(
31    example_data: &str,
32    kms_key_id: &str,
33) -> Result<(), crate::BoxError> {
34    // 1. Instantiate the encryption SDK client.
35    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
36    // which enforces that this client only encrypts using committing algorithm suites and enforces
37    // that this client will only decrypt encrypted messages that were created with a committing
38    // algorithm suite.
39    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
40    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
41
42    // 2. Create a KMS client.
43    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
44    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
45
46    // 3. Create encryption context.
47    // Remember that your encryption context is NOT SECRET.
48    // For more information, see
49    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
50    let encryption_context = HashMap::from([
51        ("encryption".to_string(), "context".to_string()),
52        ("is not".to_string(), "secret".to_string()),
53        ("but adds".to_string(), "useful metadata".to_string()),
54        (
55            "that can help you".to_string(),
56            "be confident that".to_string(),
57        ),
58        (
59            "the data you are handling".to_string(),
60            "is what you think it is".to_string(),
61        ),
62    ]);
63
64    // 4. Create a KMS keyring
65    let mpl_config = MaterialProvidersConfig::builder().build()?;
66    let mpl = mpl_client::Client::from_conf(mpl_config)?;
67
68    let kms_keyring = mpl
69        .create_aws_kms_keyring()
70        .kms_key_id(kms_key_id)
71        .kms_client(kms_client)
72        .send()
73        .await?;
74
75    // 5. Encrypt the data with the encryption_context
76    let plaintext = example_data.as_bytes();
77
78    let encryption_response = esdk_client
79        .encrypt()
80        .plaintext(plaintext)
81        .keyring(kms_keyring.clone())
82        .encryption_context(encryption_context.clone())
83        .send()
84        .await?;
85
86    let ciphertext = encryption_response
87        .ciphertext
88        .expect("Unable to unwrap ciphertext from encryption response");
89
90    // 6. Demonstrate that the ciphertext and plaintext are different.
91    // (This is an example for demonstration; you do not need to do this in your own code.)
92    assert_ne!(
93        ciphertext,
94        aws_smithy_types::Blob::new(plaintext),
95        "Ciphertext and plaintext data are the same. Invalid encryption"
96    );
97
98    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
99    let decryption_response = esdk_client
100        .decrypt()
101        .ciphertext(ciphertext)
102        .keyring(kms_keyring)
103        // Provide the encryption context that was supplied to the encrypt method
104        .encryption_context(encryption_context)
105        .send()
106        .await?;
107
108    let decrypted_plaintext = decryption_response
109        .plaintext
110        .expect("Unable to unwrap plaintext from decryption response");
111
112    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
113    // (This is an example for demonstration; you do not need to do this in your own code.)
114    assert_eq!(
115        decrypted_plaintext,
116        aws_smithy_types::Blob::new(plaintext),
117        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
118    );
119
120    println!("KMS Keyring Example Completed Successfully");
121
122    Ok(())
123}
More examples
Hide additional examples
examples/keyring/aws_kms_rsa_keyring_example.rs (line 108)
28pub async fn encrypt_and_decrypt_with_keyring(
29    example_data: &str,
30    kms_rsa_key_id: &str,
31    kms_rsa_public_key: &str,
32) -> Result<(), crate::BoxError> {
33    // 1. Instantiate the encryption SDK client.
34    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
35    // which enforces that this client only encrypts using committing algorithm suites and enforces
36    // that this client will only decrypt encrypted messages that were created with a committing
37    // algorithm suite.
38    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
39    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
40
41    // 2. Create a KMS client.
42    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
43    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
44
45    // 3. Create encryption context.
46    // Remember that your encryption context is NOT SECRET.
47    // For more information, see
48    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
49    let encryption_context = HashMap::from([
50        ("encryption".to_string(), "context".to_string()),
51        ("is not".to_string(), "secret".to_string()),
52        ("but adds".to_string(), "useful metadata".to_string()),
53        (
54            "that can help you".to_string(),
55            "be confident that".to_string(),
56        ),
57        (
58            "the data you are handling".to_string(),
59            "is what you think it is".to_string(),
60        ),
61    ]);
62
63    // 4. Create a KMS RSA keyring
64    let mpl_config = MaterialProvidersConfig::builder().build()?;
65    let mpl = mpl_client::Client::from_conf(mpl_config)?;
66
67    // For more information on the allowed encryption algorithms, please see
68    // https://docs.aws.amazon.com/kms/latest/developerguide/asymmetric-key-specs.html#key-spec-rsa
69    let kms_rsa_keyring = mpl
70        .create_aws_kms_rsa_keyring()
71        .kms_key_id(kms_rsa_key_id)
72        .public_key(aws_smithy_types::Blob::new(kms_rsa_public_key))
73        .encryption_algorithm(aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256)
74        .kms_client(kms_client)
75        .send()
76        .await?;
77
78    // 5. Encrypt the data with the encryption_context
79    let plaintext = example_data.as_bytes();
80
81    let encryption_response = esdk_client
82        .encrypt()
83        .plaintext(plaintext)
84        .keyring(kms_rsa_keyring.clone())
85        .encryption_context(encryption_context.clone())
86        .algorithm_suite_id(EsdkAlgorithmSuiteId::AlgAes256GcmHkdfSha512CommitKey)
87        .send()
88        .await?;
89
90    let ciphertext = encryption_response
91        .ciphertext
92        .expect("Unable to unwrap ciphertext from encryption response");
93
94    // 6. Demonstrate that the ciphertext and plaintext are different.
95    // (This is an example for demonstration; you do not need to do this in your own code.)
96    assert_ne!(
97        ciphertext,
98        aws_smithy_types::Blob::new(plaintext),
99        "Ciphertext and plaintext data are the same. Invalid encryption"
100    );
101
102    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
103    let decryption_response = esdk_client
104        .decrypt()
105        .ciphertext(ciphertext)
106        .keyring(kms_rsa_keyring)
107        // Provide the encryption context that was supplied to the encrypt method
108        .encryption_context(encryption_context)
109        .send()
110        .await?;
111
112    let decrypted_plaintext = decryption_response
113        .plaintext
114        .expect("Unable to unwrap plaintext from decryption response");
115
116    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
117    // (This is an example for demonstration; you do not need to do this in your own code.)
118    assert_eq!(
119        decrypted_plaintext,
120        aws_smithy_types::Blob::new(plaintext),
121        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
122    );
123
124    println!("KMS RSA Keyring Example Completed Successfully");
125
126    Ok(())
127}
examples/keyring/raw_aes_keyring_example.rs (line 115)
34pub async fn encrypt_and_decrypt_with_keyring(example_data: &str) -> Result<(), crate::BoxError> {
35    // 1. Instantiate the encryption SDK client.
36    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
37    // which enforces that this client only encrypts using committing algorithm suites and enforces
38    // that this client will only decrypt encrypted messages that were created with a committing
39    // algorithm suite.
40    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
41    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
42
43    // 2. The key namespace and key name are defined by you.
44    // and are used by the Raw AES keyring to determine
45    // whether it should attempt to decrypt an encrypted data key.
46    // For more information, see
47    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html
48    let key_namespace: &str = "my-key-namespace";
49    let key_name: &str = "my-aes-key-name";
50
51    // 3. Create encryption context.
52    // Remember that your encryption context is NOT SECRET.
53    // For more information, see
54    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
55    let encryption_context = HashMap::from([
56        ("encryption".to_string(), "context".to_string()),
57        ("is not".to_string(), "secret".to_string()),
58        ("but adds".to_string(), "useful metadata".to_string()),
59        (
60            "that can help you".to_string(),
61            "be confident that".to_string(),
62        ),
63        (
64            "the data you are handling".to_string(),
65            "is what you think it is".to_string(),
66        ),
67    ]);
68
69    // 4. Generate a 256-bit AES key to use with your keyring.
70    // In practice, you should get this key from a secure key management system such as an HSM.
71    let aes_key_bytes = generate_aes_key_bytes();
72
73    // 5. Create a Raw AES Keyring
74    let mpl_config = MaterialProvidersConfig::builder().build()?;
75    let mpl = mpl_client::Client::from_conf(mpl_config)?;
76
77    let raw_aes_keyring = mpl
78        .create_raw_aes_keyring()
79        .key_name(key_name)
80        .key_namespace(key_namespace)
81        .wrapping_key(aes_key_bytes)
82        .wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
83        .send()
84        .await?;
85
86    // 6. Encrypt the data with the encryption_context
87    let plaintext = example_data.as_bytes();
88
89    let encryption_response = esdk_client
90        .encrypt()
91        .plaintext(plaintext)
92        .keyring(raw_aes_keyring.clone())
93        .encryption_context(encryption_context.clone())
94        .send()
95        .await?;
96
97    let ciphertext = encryption_response
98        .ciphertext
99        .expect("Unable to unwrap ciphertext from encryption response");
100
101    // 7. Demonstrate that the ciphertext and plaintext are different.
102    // (This is an example for demonstration; you do not need to do this in your own code.)
103    assert_ne!(
104        ciphertext,
105        aws_smithy_types::Blob::new(plaintext),
106        "Ciphertext and plaintext data are the same. Invalid encryption"
107    );
108
109    // 8. Decrypt your encrypted data using the same keyring you used on encrypt.
110    let decryption_response = esdk_client
111        .decrypt()
112        .ciphertext(ciphertext)
113        .keyring(raw_aes_keyring)
114        // Provide the encryption context that was supplied to the encrypt method
115        .encryption_context(encryption_context)
116        .send()
117        .await?;
118
119    let decrypted_plaintext = decryption_response
120        .plaintext
121        .expect("Unable to unwrap plaintext from decryption response");
122
123    // 9. Demonstrate that the decrypted plaintext is identical to the original plaintext.
124    // (This is an example for demonstration; you do not need to do this in your own code.)
125    assert_eq!(
126        decrypted_plaintext,
127        aws_smithy_types::Blob::new(plaintext),
128        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
129    );
130
131    println!("Raw AES Keyring Example Completed Successfully");
132
133    Ok(())
134}
examples/set_encryption_algorithm_suite_example.rs (line 136)
51pub async fn encrypt_and_decrypt_with_keyring(example_data: &str) -> Result<(), crate::BoxError> {
52    // 1. Instantiate the encryption SDK client.
53    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
54    // which enforces that this client only encrypts using committing algorithm suites and enforces
55    // that this client will only decrypt encrypted messages that were created with a committing
56    // algorithm suite.
57    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
58    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
59
60    // 2. The key namespace and key name are defined by you.
61    // and are used by the Raw AES keyring to determine
62    // whether it should attempt to decrypt an encrypted data key.
63    // For more information, see
64    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html
65    let key_namespace: &str = "my-key-namespace";
66    let key_name: &str = "my-aes-key-name";
67
68    // 3. Create encryption context.
69    // Remember that your encryption context is NOT SECRET.
70    // For more information, see
71    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
72    let encryption_context = HashMap::from([
73        ("encryption".to_string(), "context".to_string()),
74        ("is not".to_string(), "secret".to_string()),
75        ("but adds".to_string(), "useful metadata".to_string()),
76        (
77            "that can help you".to_string(),
78            "be confident that".to_string(),
79        ),
80        (
81            "the data you are handling".to_string(),
82            "is what you think it is".to_string(),
83        ),
84    ]);
85
86    // 4. Generate a 256-bit AES key to use with your keyring.
87    // In practice, you should get this key from a secure key management system such as an HSM.
88    let aes_key_bytes = generate_aes_key_bytes();
89
90    // 5. Create a Raw AES Keyring
91    let mpl_config = MaterialProvidersConfig::builder().build()?;
92    let mpl = mpl_client::Client::from_conf(mpl_config)?;
93
94    // The wrapping algorithm here is NOT the algorithm suite we set in this example.
95    let raw_aes_keyring = mpl
96        .create_raw_aes_keyring()
97        .key_name(key_name)
98        .key_namespace(key_namespace)
99        .wrapping_key(aes_key_bytes)
100        .wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
101        .send()
102        .await?;
103
104    // 6. Encrypt the data with the encryption_context
105    let plaintext = example_data.as_bytes();
106
107    // This is the important step in this example where we specify the algorithm suite
108    // you want to use for encrypting your data
109    let encryption_response = esdk_client
110        .encrypt()
111        .plaintext(plaintext)
112        .keyring(raw_aes_keyring.clone())
113        .encryption_context(encryption_context.clone())
114        .algorithm_suite_id(AlgAes256GcmHkdfSha512CommitKey)
115        .send()
116        .await?;
117
118    let ciphertext = encryption_response
119        .ciphertext
120        .expect("Unable to unwrap ciphertext from encryption response");
121
122    // 7. Demonstrate that the ciphertext and plaintext are different.
123    // (This is an example for demonstration; you do not need to do this in your own code.)
124    assert_ne!(
125        ciphertext,
126        aws_smithy_types::Blob::new(plaintext),
127        "Ciphertext and plaintext data are the same. Invalid encryption"
128    );
129
130    // 8. Decrypt your encrypted data using the same keyring you used on encrypt.
131    let decryption_response = esdk_client
132        .decrypt()
133        .ciphertext(ciphertext)
134        .keyring(raw_aes_keyring)
135        // Provide the encryption context that was supplied to the encrypt method
136        .encryption_context(encryption_context)
137        .send()
138        .await?;
139
140    let decrypted_plaintext = decryption_response
141        .plaintext
142        .expect("Unable to unwrap plaintext from decryption response");
143
144    // 9. Demonstrate that the decrypted plaintext is identical to the original plaintext.
145    // (This is an example for demonstration; you do not need to do this in your own code.)
146    assert_eq!(
147        decrypted_plaintext,
148        aws_smithy_types::Blob::new(plaintext),
149        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
150    );
151
152    println!("Set Encryption Algorithm Suite Example Completed Successfully");
153
154    Ok(())
155}
examples/set_commitment_policy_example.rs (line 123)
34pub async fn encrypt_and_decrypt_with_keyring(
35    example_data: &str,
36    kms_key_id: &str,
37) -> Result<(), crate::BoxError> {
38    // 1. Instantiate the encryption SDK client.
39    // This example builds the client with the ForbidEncryptAllowDecrypt commitment policy,
40    // which enforces that this client cannot encrypt with key commitment
41    // and it can decrypt ciphertexts encrypted with or without key commitment.
42    // The default commitment policy if you were to build the client like in
43    // the `keyring/aws_kms_keyring_example.rs` is RequireEncryptRequireDecrypt.
44    // We recommend that AWS Encryption SDK users use the default commitment policy
45    // (RequireEncryptRequireDecrypt) whenever possible.
46    let esdk_config = AwsEncryptionSdkConfig::builder()
47        .commitment_policy(ForbidEncryptAllowDecrypt)
48        .build()?;
49    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
50
51    // 2. Create a KMS client.
52    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
53    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
54
55    // 3. Create encryption context.
56    // Remember that your encryption context is NOT SECRET.
57    // For more information, see
58    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
59    let encryption_context = HashMap::from([
60        ("encryption".to_string(), "context".to_string()),
61        ("is not".to_string(), "secret".to_string()),
62        ("but adds".to_string(), "useful metadata".to_string()),
63        (
64            "that can help you".to_string(),
65            "be confident that".to_string(),
66        ),
67        (
68            "the data you are handling".to_string(),
69            "is what you think it is".to_string(),
70        ),
71    ]);
72
73    // 4. Create a KMS keyring
74    let mpl_config = MaterialProvidersConfig::builder().build()?;
75    let mpl = mpl_client::Client::from_conf(mpl_config)?;
76
77    let kms_keyring = mpl
78        .create_aws_kms_keyring()
79        .kms_key_id(kms_key_id)
80        .kms_client(kms_client)
81        .send()
82        .await?;
83
84    // 5. Encrypt the data with the encryption_context. Make sure you use a non-committing algorithm
85    // with the commitment policy ForbidEncryptAllowDecrypt. Otherwise esdk_client.encrypt() will throw
86    // Error: AwsCryptographicMaterialProvidersError
87    //   {
88    //     error: InvalidAlgorithmSuiteInfoOnEncrypt
89    //     {
90    //       message: "Configuration conflict. Commitment policy requires only non-committing algorithm suites"
91    //     }
92    //   }
93    // By default for ForbidEncryptAllowDecrypt, the algorithm used is
94    // AlgAes256GcmIv12Tag16HkdfSha384EcdsaP384 which is a non-committing algorithm.
95    let plaintext = example_data.as_bytes();
96
97    let encryption_response = esdk_client
98        .encrypt()
99        .plaintext(plaintext)
100        .keyring(kms_keyring.clone())
101        .encryption_context(encryption_context.clone())
102        .send()
103        .await?;
104
105    let ciphertext = encryption_response
106        .ciphertext
107        .expect("Unable to unwrap ciphertext from encryption response");
108
109    // 6. Demonstrate that the ciphertext and plaintext are different.
110    // (This is an example for demonstration; you do not need to do this in your own code.)
111    assert_ne!(
112        ciphertext,
113        aws_smithy_types::Blob::new(plaintext),
114        "Ciphertext and plaintext data are the same. Invalid encryption"
115    );
116
117    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
118    let decryption_response = esdk_client
119        .decrypt()
120        .ciphertext(ciphertext)
121        .keyring(kms_keyring)
122        // Provide the encryption context that was supplied to the encrypt method
123        .encryption_context(encryption_context)
124        .send()
125        .await?;
126
127    let decrypted_plaintext = decryption_response
128        .plaintext
129        .expect("Unable to unwrap plaintext from decryption response");
130
131    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
132    // (This is an example for demonstration; you do not need to do this in your own code.)
133    assert_eq!(
134        decrypted_plaintext,
135        aws_smithy_types::Blob::new(plaintext),
136        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
137    );
138
139    println!("Set Commitment Policy Example Completed Successfully");
140
141    Ok(())
142}
examples/keyring/ecdh/public_key_discovery_raw_ecdh_keyring_example.rs (line 156)
66pub async fn decrypt_with_keyring(
67    example_data: &str,
68    ecdh_curve_spec: EcdhCurveSpec,
69) -> Result<(), crate::BoxError> {
70    // 1. Instantiate the encryption SDK client.
71    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
72    // which enforces that this client only encrypts using committing algorithm suites and enforces
73    // that this client will only decrypt encrypted messages that were created with a committing
74    // algorithm suite.
75    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
76    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
77
78    let mpl_config = MaterialProvidersConfig::builder().build()?;
79    let mpl = mpl_client::Client::from_conf(mpl_config)?;
80
81    // 2. Create encryption context.
82    // Remember that your encryption context is NOT SECRET.
83    // For more information, see
84    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
85    let encryption_context = HashMap::from([
86        ("encryption".to_string(), "context".to_string()),
87        ("is not".to_string(), "secret".to_string()),
88        ("but adds".to_string(), "useful metadata".to_string()),
89        (
90            "that can help you".to_string(),
91            "be confident that".to_string(),
92        ),
93        (
94            "the data you are handling".to_string(),
95            "is what you think it is".to_string(),
96        ),
97    ]);
98
99    // 3. You may provide your own ECC keys in the files located at
100    // - EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT
101
102    // If you do not provide these files, running this example through this
103    // class' main method will generate three files required for all raw ECDH examples
104    // EXAMPLE_ECC_PRIVATE_KEY_FILENAME_SENDER, EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT
105    // and EXAMPLE_ECC_PUBLIC_KEY_FILENAME_RECIPIENT for you.
106
107    // Do not use these files for any other purpose.
108    if should_generate_new_ecc_key_pair_discovery_raw_ecdh()? {
109        write_raw_ecdh_ecc_keys(ecdh_curve_spec)?;
110    }
111
112    // 4. Load keys from UTF-8 encoded PEM files.
113    let mut file = File::open(Path::new(EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT))?;
114    let mut private_key_recipient_utf8_bytes = Vec::new();
115    file.read_to_end(&mut private_key_recipient_utf8_bytes)?;
116
117    // Generate the ciphertext
118    let ciphertext = get_ciphertext(
119        example_data,
120        ecdh_curve_spec,
121        encryption_context.clone(),
122        esdk_client.clone(),
123        mpl.clone(),
124    )
125    .await?;
126
127    // 5. Create the PublicKeyDiscoveryInput
128    let discovery_raw_ecdh_static_configuration_input = PublicKeyDiscoveryInput::builder()
129        // Must be a UTF8 PEM-encoded private key
130        .recipient_static_private_key(private_key_recipient_utf8_bytes)
131        .build()?;
132
133    let discovery_raw_ecdh_static_configuration = RawEcdhStaticConfigurations::PublicKeyDiscovery(
134        discovery_raw_ecdh_static_configuration_input,
135    );
136
137    // 6. Create the Public Key Discovery Raw ECDH keyring.
138
139    // Create the keyring.
140    // This keyring uses a discovery configuration. This configuration will check on decrypt
141    // if it is meant to decrypt the message by checking if the configured public key is stored on the message.
142    // The discovery configuration can only decrypt messages and CANNOT encrypt messages.
143    let discovery_raw_ecdh_keyring = mpl
144        .create_raw_ecdh_keyring()
145        .curve_spec(ecdh_curve_spec)
146        .key_agreement_scheme(discovery_raw_ecdh_static_configuration)
147        .send()
148        .await?;
149
150    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
151    let decryption_response = esdk_client
152        .decrypt()
153        .ciphertext(ciphertext)
154        .keyring(discovery_raw_ecdh_keyring)
155        // Provide the encryption context that was supplied to the encrypt method
156        .encryption_context(encryption_context)
157        .send()
158        .await?;
159
160    let decrypted_plaintext = decryption_response
161        .plaintext
162        .expect("Unable to unwrap plaintext from decryption response");
163
164    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
165    // (This is an example for demonstration; you do not need to do this in your own code.)
166    let plaintext = example_data.as_bytes();
167
168    assert_eq!(
169        decrypted_plaintext,
170        aws_smithy_types::Blob::new(plaintext),
171        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
172    );
173
174    println!("Public Key Discovery Raw ECDH Keyring Example Completed Successfully");
175
176    Ok(())
177}
Source

pub fn set_encryption_context( self, input: Option<HashMap<String, String>>, ) -> Self

Source

pub fn get_encryption_context(&self) -> &Option<HashMap<String, String>>

Source

pub fn keyring(self, input: impl Into<KeyringRef>) -> Self

Examples found in repository?
examples/keyring/aws_kms_keyring_example.rs (line 102)
30pub async fn encrypt_and_decrypt_with_keyring(
31    example_data: &str,
32    kms_key_id: &str,
33) -> Result<(), crate::BoxError> {
34    // 1. Instantiate the encryption SDK client.
35    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
36    // which enforces that this client only encrypts using committing algorithm suites and enforces
37    // that this client will only decrypt encrypted messages that were created with a committing
38    // algorithm suite.
39    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
40    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
41
42    // 2. Create a KMS client.
43    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
44    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
45
46    // 3. Create encryption context.
47    // Remember that your encryption context is NOT SECRET.
48    // For more information, see
49    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
50    let encryption_context = HashMap::from([
51        ("encryption".to_string(), "context".to_string()),
52        ("is not".to_string(), "secret".to_string()),
53        ("but adds".to_string(), "useful metadata".to_string()),
54        (
55            "that can help you".to_string(),
56            "be confident that".to_string(),
57        ),
58        (
59            "the data you are handling".to_string(),
60            "is what you think it is".to_string(),
61        ),
62    ]);
63
64    // 4. Create a KMS keyring
65    let mpl_config = MaterialProvidersConfig::builder().build()?;
66    let mpl = mpl_client::Client::from_conf(mpl_config)?;
67
68    let kms_keyring = mpl
69        .create_aws_kms_keyring()
70        .kms_key_id(kms_key_id)
71        .kms_client(kms_client)
72        .send()
73        .await?;
74
75    // 5. Encrypt the data with the encryption_context
76    let plaintext = example_data.as_bytes();
77
78    let encryption_response = esdk_client
79        .encrypt()
80        .plaintext(plaintext)
81        .keyring(kms_keyring.clone())
82        .encryption_context(encryption_context.clone())
83        .send()
84        .await?;
85
86    let ciphertext = encryption_response
87        .ciphertext
88        .expect("Unable to unwrap ciphertext from encryption response");
89
90    // 6. Demonstrate that the ciphertext and plaintext are different.
91    // (This is an example for demonstration; you do not need to do this in your own code.)
92    assert_ne!(
93        ciphertext,
94        aws_smithy_types::Blob::new(plaintext),
95        "Ciphertext and plaintext data are the same. Invalid encryption"
96    );
97
98    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
99    let decryption_response = esdk_client
100        .decrypt()
101        .ciphertext(ciphertext)
102        .keyring(kms_keyring)
103        // Provide the encryption context that was supplied to the encrypt method
104        .encryption_context(encryption_context)
105        .send()
106        .await?;
107
108    let decrypted_plaintext = decryption_response
109        .plaintext
110        .expect("Unable to unwrap plaintext from decryption response");
111
112    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
113    // (This is an example for demonstration; you do not need to do this in your own code.)
114    assert_eq!(
115        decrypted_plaintext,
116        aws_smithy_types::Blob::new(plaintext),
117        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
118    );
119
120    println!("KMS Keyring Example Completed Successfully");
121
122    Ok(())
123}
More examples
Hide additional examples
examples/keyring/aws_kms_rsa_keyring_example.rs (line 106)
28pub async fn encrypt_and_decrypt_with_keyring(
29    example_data: &str,
30    kms_rsa_key_id: &str,
31    kms_rsa_public_key: &str,
32) -> Result<(), crate::BoxError> {
33    // 1. Instantiate the encryption SDK client.
34    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
35    // which enforces that this client only encrypts using committing algorithm suites and enforces
36    // that this client will only decrypt encrypted messages that were created with a committing
37    // algorithm suite.
38    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
39    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
40
41    // 2. Create a KMS client.
42    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
43    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
44
45    // 3. Create encryption context.
46    // Remember that your encryption context is NOT SECRET.
47    // For more information, see
48    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
49    let encryption_context = HashMap::from([
50        ("encryption".to_string(), "context".to_string()),
51        ("is not".to_string(), "secret".to_string()),
52        ("but adds".to_string(), "useful metadata".to_string()),
53        (
54            "that can help you".to_string(),
55            "be confident that".to_string(),
56        ),
57        (
58            "the data you are handling".to_string(),
59            "is what you think it is".to_string(),
60        ),
61    ]);
62
63    // 4. Create a KMS RSA keyring
64    let mpl_config = MaterialProvidersConfig::builder().build()?;
65    let mpl = mpl_client::Client::from_conf(mpl_config)?;
66
67    // For more information on the allowed encryption algorithms, please see
68    // https://docs.aws.amazon.com/kms/latest/developerguide/asymmetric-key-specs.html#key-spec-rsa
69    let kms_rsa_keyring = mpl
70        .create_aws_kms_rsa_keyring()
71        .kms_key_id(kms_rsa_key_id)
72        .public_key(aws_smithy_types::Blob::new(kms_rsa_public_key))
73        .encryption_algorithm(aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256)
74        .kms_client(kms_client)
75        .send()
76        .await?;
77
78    // 5. Encrypt the data with the encryption_context
79    let plaintext = example_data.as_bytes();
80
81    let encryption_response = esdk_client
82        .encrypt()
83        .plaintext(plaintext)
84        .keyring(kms_rsa_keyring.clone())
85        .encryption_context(encryption_context.clone())
86        .algorithm_suite_id(EsdkAlgorithmSuiteId::AlgAes256GcmHkdfSha512CommitKey)
87        .send()
88        .await?;
89
90    let ciphertext = encryption_response
91        .ciphertext
92        .expect("Unable to unwrap ciphertext from encryption response");
93
94    // 6. Demonstrate that the ciphertext and plaintext are different.
95    // (This is an example for demonstration; you do not need to do this in your own code.)
96    assert_ne!(
97        ciphertext,
98        aws_smithy_types::Blob::new(plaintext),
99        "Ciphertext and plaintext data are the same. Invalid encryption"
100    );
101
102    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
103    let decryption_response = esdk_client
104        .decrypt()
105        .ciphertext(ciphertext)
106        .keyring(kms_rsa_keyring)
107        // Provide the encryption context that was supplied to the encrypt method
108        .encryption_context(encryption_context)
109        .send()
110        .await?;
111
112    let decrypted_plaintext = decryption_response
113        .plaintext
114        .expect("Unable to unwrap plaintext from decryption response");
115
116    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
117    // (This is an example for demonstration; you do not need to do this in your own code.)
118    assert_eq!(
119        decrypted_plaintext,
120        aws_smithy_types::Blob::new(plaintext),
121        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
122    );
123
124    println!("KMS RSA Keyring Example Completed Successfully");
125
126    Ok(())
127}
examples/keyring/raw_aes_keyring_example.rs (line 113)
34pub async fn encrypt_and_decrypt_with_keyring(example_data: &str) -> Result<(), crate::BoxError> {
35    // 1. Instantiate the encryption SDK client.
36    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
37    // which enforces that this client only encrypts using committing algorithm suites and enforces
38    // that this client will only decrypt encrypted messages that were created with a committing
39    // algorithm suite.
40    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
41    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
42
43    // 2. The key namespace and key name are defined by you.
44    // and are used by the Raw AES keyring to determine
45    // whether it should attempt to decrypt an encrypted data key.
46    // For more information, see
47    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html
48    let key_namespace: &str = "my-key-namespace";
49    let key_name: &str = "my-aes-key-name";
50
51    // 3. Create encryption context.
52    // Remember that your encryption context is NOT SECRET.
53    // For more information, see
54    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
55    let encryption_context = HashMap::from([
56        ("encryption".to_string(), "context".to_string()),
57        ("is not".to_string(), "secret".to_string()),
58        ("but adds".to_string(), "useful metadata".to_string()),
59        (
60            "that can help you".to_string(),
61            "be confident that".to_string(),
62        ),
63        (
64            "the data you are handling".to_string(),
65            "is what you think it is".to_string(),
66        ),
67    ]);
68
69    // 4. Generate a 256-bit AES key to use with your keyring.
70    // In practice, you should get this key from a secure key management system such as an HSM.
71    let aes_key_bytes = generate_aes_key_bytes();
72
73    // 5. Create a Raw AES Keyring
74    let mpl_config = MaterialProvidersConfig::builder().build()?;
75    let mpl = mpl_client::Client::from_conf(mpl_config)?;
76
77    let raw_aes_keyring = mpl
78        .create_raw_aes_keyring()
79        .key_name(key_name)
80        .key_namespace(key_namespace)
81        .wrapping_key(aes_key_bytes)
82        .wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
83        .send()
84        .await?;
85
86    // 6. Encrypt the data with the encryption_context
87    let plaintext = example_data.as_bytes();
88
89    let encryption_response = esdk_client
90        .encrypt()
91        .plaintext(plaintext)
92        .keyring(raw_aes_keyring.clone())
93        .encryption_context(encryption_context.clone())
94        .send()
95        .await?;
96
97    let ciphertext = encryption_response
98        .ciphertext
99        .expect("Unable to unwrap ciphertext from encryption response");
100
101    // 7. Demonstrate that the ciphertext and plaintext are different.
102    // (This is an example for demonstration; you do not need to do this in your own code.)
103    assert_ne!(
104        ciphertext,
105        aws_smithy_types::Blob::new(plaintext),
106        "Ciphertext and plaintext data are the same. Invalid encryption"
107    );
108
109    // 8. Decrypt your encrypted data using the same keyring you used on encrypt.
110    let decryption_response = esdk_client
111        .decrypt()
112        .ciphertext(ciphertext)
113        .keyring(raw_aes_keyring)
114        // Provide the encryption context that was supplied to the encrypt method
115        .encryption_context(encryption_context)
116        .send()
117        .await?;
118
119    let decrypted_plaintext = decryption_response
120        .plaintext
121        .expect("Unable to unwrap plaintext from decryption response");
122
123    // 9. Demonstrate that the decrypted plaintext is identical to the original plaintext.
124    // (This is an example for demonstration; you do not need to do this in your own code.)
125    assert_eq!(
126        decrypted_plaintext,
127        aws_smithy_types::Blob::new(plaintext),
128        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
129    );
130
131    println!("Raw AES Keyring Example Completed Successfully");
132
133    Ok(())
134}
examples/set_encryption_algorithm_suite_example.rs (line 134)
51pub async fn encrypt_and_decrypt_with_keyring(example_data: &str) -> Result<(), crate::BoxError> {
52    // 1. Instantiate the encryption SDK client.
53    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
54    // which enforces that this client only encrypts using committing algorithm suites and enforces
55    // that this client will only decrypt encrypted messages that were created with a committing
56    // algorithm suite.
57    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
58    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
59
60    // 2. The key namespace and key name are defined by you.
61    // and are used by the Raw AES keyring to determine
62    // whether it should attempt to decrypt an encrypted data key.
63    // For more information, see
64    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-raw-aes-keyring.html
65    let key_namespace: &str = "my-key-namespace";
66    let key_name: &str = "my-aes-key-name";
67
68    // 3. Create encryption context.
69    // Remember that your encryption context is NOT SECRET.
70    // For more information, see
71    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
72    let encryption_context = HashMap::from([
73        ("encryption".to_string(), "context".to_string()),
74        ("is not".to_string(), "secret".to_string()),
75        ("but adds".to_string(), "useful metadata".to_string()),
76        (
77            "that can help you".to_string(),
78            "be confident that".to_string(),
79        ),
80        (
81            "the data you are handling".to_string(),
82            "is what you think it is".to_string(),
83        ),
84    ]);
85
86    // 4. Generate a 256-bit AES key to use with your keyring.
87    // In practice, you should get this key from a secure key management system such as an HSM.
88    let aes_key_bytes = generate_aes_key_bytes();
89
90    // 5. Create a Raw AES Keyring
91    let mpl_config = MaterialProvidersConfig::builder().build()?;
92    let mpl = mpl_client::Client::from_conf(mpl_config)?;
93
94    // The wrapping algorithm here is NOT the algorithm suite we set in this example.
95    let raw_aes_keyring = mpl
96        .create_raw_aes_keyring()
97        .key_name(key_name)
98        .key_namespace(key_namespace)
99        .wrapping_key(aes_key_bytes)
100        .wrapping_alg(AesWrappingAlg::AlgAes256GcmIv12Tag16)
101        .send()
102        .await?;
103
104    // 6. Encrypt the data with the encryption_context
105    let plaintext = example_data.as_bytes();
106
107    // This is the important step in this example where we specify the algorithm suite
108    // you want to use for encrypting your data
109    let encryption_response = esdk_client
110        .encrypt()
111        .plaintext(plaintext)
112        .keyring(raw_aes_keyring.clone())
113        .encryption_context(encryption_context.clone())
114        .algorithm_suite_id(AlgAes256GcmHkdfSha512CommitKey)
115        .send()
116        .await?;
117
118    let ciphertext = encryption_response
119        .ciphertext
120        .expect("Unable to unwrap ciphertext from encryption response");
121
122    // 7. Demonstrate that the ciphertext and plaintext are different.
123    // (This is an example for demonstration; you do not need to do this in your own code.)
124    assert_ne!(
125        ciphertext,
126        aws_smithy_types::Blob::new(plaintext),
127        "Ciphertext and plaintext data are the same. Invalid encryption"
128    );
129
130    // 8. Decrypt your encrypted data using the same keyring you used on encrypt.
131    let decryption_response = esdk_client
132        .decrypt()
133        .ciphertext(ciphertext)
134        .keyring(raw_aes_keyring)
135        // Provide the encryption context that was supplied to the encrypt method
136        .encryption_context(encryption_context)
137        .send()
138        .await?;
139
140    let decrypted_plaintext = decryption_response
141        .plaintext
142        .expect("Unable to unwrap plaintext from decryption response");
143
144    // 9. Demonstrate that the decrypted plaintext is identical to the original plaintext.
145    // (This is an example for demonstration; you do not need to do this in your own code.)
146    assert_eq!(
147        decrypted_plaintext,
148        aws_smithy_types::Blob::new(plaintext),
149        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
150    );
151
152    println!("Set Encryption Algorithm Suite Example Completed Successfully");
153
154    Ok(())
155}
examples/set_commitment_policy_example.rs (line 121)
34pub async fn encrypt_and_decrypt_with_keyring(
35    example_data: &str,
36    kms_key_id: &str,
37) -> Result<(), crate::BoxError> {
38    // 1. Instantiate the encryption SDK client.
39    // This example builds the client with the ForbidEncryptAllowDecrypt commitment policy,
40    // which enforces that this client cannot encrypt with key commitment
41    // and it can decrypt ciphertexts encrypted with or without key commitment.
42    // The default commitment policy if you were to build the client like in
43    // the `keyring/aws_kms_keyring_example.rs` is RequireEncryptRequireDecrypt.
44    // We recommend that AWS Encryption SDK users use the default commitment policy
45    // (RequireEncryptRequireDecrypt) whenever possible.
46    let esdk_config = AwsEncryptionSdkConfig::builder()
47        .commitment_policy(ForbidEncryptAllowDecrypt)
48        .build()?;
49    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
50
51    // 2. Create a KMS client.
52    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
53    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
54
55    // 3. Create encryption context.
56    // Remember that your encryption context is NOT SECRET.
57    // For more information, see
58    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
59    let encryption_context = HashMap::from([
60        ("encryption".to_string(), "context".to_string()),
61        ("is not".to_string(), "secret".to_string()),
62        ("but adds".to_string(), "useful metadata".to_string()),
63        (
64            "that can help you".to_string(),
65            "be confident that".to_string(),
66        ),
67        (
68            "the data you are handling".to_string(),
69            "is what you think it is".to_string(),
70        ),
71    ]);
72
73    // 4. Create a KMS keyring
74    let mpl_config = MaterialProvidersConfig::builder().build()?;
75    let mpl = mpl_client::Client::from_conf(mpl_config)?;
76
77    let kms_keyring = mpl
78        .create_aws_kms_keyring()
79        .kms_key_id(kms_key_id)
80        .kms_client(kms_client)
81        .send()
82        .await?;
83
84    // 5. Encrypt the data with the encryption_context. Make sure you use a non-committing algorithm
85    // with the commitment policy ForbidEncryptAllowDecrypt. Otherwise esdk_client.encrypt() will throw
86    // Error: AwsCryptographicMaterialProvidersError
87    //   {
88    //     error: InvalidAlgorithmSuiteInfoOnEncrypt
89    //     {
90    //       message: "Configuration conflict. Commitment policy requires only non-committing algorithm suites"
91    //     }
92    //   }
93    // By default for ForbidEncryptAllowDecrypt, the algorithm used is
94    // AlgAes256GcmIv12Tag16HkdfSha384EcdsaP384 which is a non-committing algorithm.
95    let plaintext = example_data.as_bytes();
96
97    let encryption_response = esdk_client
98        .encrypt()
99        .plaintext(plaintext)
100        .keyring(kms_keyring.clone())
101        .encryption_context(encryption_context.clone())
102        .send()
103        .await?;
104
105    let ciphertext = encryption_response
106        .ciphertext
107        .expect("Unable to unwrap ciphertext from encryption response");
108
109    // 6. Demonstrate that the ciphertext and plaintext are different.
110    // (This is an example for demonstration; you do not need to do this in your own code.)
111    assert_ne!(
112        ciphertext,
113        aws_smithy_types::Blob::new(plaintext),
114        "Ciphertext and plaintext data are the same. Invalid encryption"
115    );
116
117    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
118    let decryption_response = esdk_client
119        .decrypt()
120        .ciphertext(ciphertext)
121        .keyring(kms_keyring)
122        // Provide the encryption context that was supplied to the encrypt method
123        .encryption_context(encryption_context)
124        .send()
125        .await?;
126
127    let decrypted_plaintext = decryption_response
128        .plaintext
129        .expect("Unable to unwrap plaintext from decryption response");
130
131    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
132    // (This is an example for demonstration; you do not need to do this in your own code.)
133    assert_eq!(
134        decrypted_plaintext,
135        aws_smithy_types::Blob::new(plaintext),
136        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
137    );
138
139    println!("Set Commitment Policy Example Completed Successfully");
140
141    Ok(())
142}
examples/keyring/ecdh/public_key_discovery_raw_ecdh_keyring_example.rs (line 154)
66pub async fn decrypt_with_keyring(
67    example_data: &str,
68    ecdh_curve_spec: EcdhCurveSpec,
69) -> Result<(), crate::BoxError> {
70    // 1. Instantiate the encryption SDK client.
71    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
72    // which enforces that this client only encrypts using committing algorithm suites and enforces
73    // that this client will only decrypt encrypted messages that were created with a committing
74    // algorithm suite.
75    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
76    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
77
78    let mpl_config = MaterialProvidersConfig::builder().build()?;
79    let mpl = mpl_client::Client::from_conf(mpl_config)?;
80
81    // 2. Create encryption context.
82    // Remember that your encryption context is NOT SECRET.
83    // For more information, see
84    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
85    let encryption_context = HashMap::from([
86        ("encryption".to_string(), "context".to_string()),
87        ("is not".to_string(), "secret".to_string()),
88        ("but adds".to_string(), "useful metadata".to_string()),
89        (
90            "that can help you".to_string(),
91            "be confident that".to_string(),
92        ),
93        (
94            "the data you are handling".to_string(),
95            "is what you think it is".to_string(),
96        ),
97    ]);
98
99    // 3. You may provide your own ECC keys in the files located at
100    // - EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT
101
102    // If you do not provide these files, running this example through this
103    // class' main method will generate three files required for all raw ECDH examples
104    // EXAMPLE_ECC_PRIVATE_KEY_FILENAME_SENDER, EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT
105    // and EXAMPLE_ECC_PUBLIC_KEY_FILENAME_RECIPIENT for you.
106
107    // Do not use these files for any other purpose.
108    if should_generate_new_ecc_key_pair_discovery_raw_ecdh()? {
109        write_raw_ecdh_ecc_keys(ecdh_curve_spec)?;
110    }
111
112    // 4. Load keys from UTF-8 encoded PEM files.
113    let mut file = File::open(Path::new(EXAMPLE_ECC_PRIVATE_KEY_FILENAME_RECIPIENT))?;
114    let mut private_key_recipient_utf8_bytes = Vec::new();
115    file.read_to_end(&mut private_key_recipient_utf8_bytes)?;
116
117    // Generate the ciphertext
118    let ciphertext = get_ciphertext(
119        example_data,
120        ecdh_curve_spec,
121        encryption_context.clone(),
122        esdk_client.clone(),
123        mpl.clone(),
124    )
125    .await?;
126
127    // 5. Create the PublicKeyDiscoveryInput
128    let discovery_raw_ecdh_static_configuration_input = PublicKeyDiscoveryInput::builder()
129        // Must be a UTF8 PEM-encoded private key
130        .recipient_static_private_key(private_key_recipient_utf8_bytes)
131        .build()?;
132
133    let discovery_raw_ecdh_static_configuration = RawEcdhStaticConfigurations::PublicKeyDiscovery(
134        discovery_raw_ecdh_static_configuration_input,
135    );
136
137    // 6. Create the Public Key Discovery Raw ECDH keyring.
138
139    // Create the keyring.
140    // This keyring uses a discovery configuration. This configuration will check on decrypt
141    // if it is meant to decrypt the message by checking if the configured public key is stored on the message.
142    // The discovery configuration can only decrypt messages and CANNOT encrypt messages.
143    let discovery_raw_ecdh_keyring = mpl
144        .create_raw_ecdh_keyring()
145        .curve_spec(ecdh_curve_spec)
146        .key_agreement_scheme(discovery_raw_ecdh_static_configuration)
147        .send()
148        .await?;
149
150    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
151    let decryption_response = esdk_client
152        .decrypt()
153        .ciphertext(ciphertext)
154        .keyring(discovery_raw_ecdh_keyring)
155        // Provide the encryption context that was supplied to the encrypt method
156        .encryption_context(encryption_context)
157        .send()
158        .await?;
159
160    let decrypted_plaintext = decryption_response
161        .plaintext
162        .expect("Unable to unwrap plaintext from decryption response");
163
164    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
165    // (This is an example for demonstration; you do not need to do this in your own code.)
166    let plaintext = example_data.as_bytes();
167
168    assert_eq!(
169        decrypted_plaintext,
170        aws_smithy_types::Blob::new(plaintext),
171        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
172    );
173
174    println!("Public Key Discovery Raw ECDH Keyring Example Completed Successfully");
175
176    Ok(())
177}
Source

pub fn set_keyring(self, input: Option<KeyringRef>) -> Self

Source

pub fn get_keyring(&self) -> &Option<KeyringRef>

Source

pub fn materials_manager( self, input: impl Into<CryptographicMaterialsManagerRef>, ) -> Self

Examples found in repository?
examples/cryptographic_materials_manager/restrict_algorithm_suite/signing_only_example.rs (line 99)
19pub async fn encrypt_and_decrypt_with_cmm(
20    example_data: &str,
21    kms_key_id: &str,
22) -> Result<(), crate::BoxError> {
23    // 1. Instantiate the encryption SDK client.
24    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
25    // which enforces that this client only encrypts using committing algorithm suites and enforces
26    // that this client will only decrypt encrypted messages that were created with a committing
27    // algorithm suite.
28    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
29    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
30
31    // 2. Create a KMS client.
32    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
33    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
34
35    // 3. Create encryption context.
36    // Remember that your encryption context is NOT SECRET.
37    // For more information, see
38    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
39    let encryption_context = HashMap::from([
40        ("encryption".to_string(), "context".to_string()),
41        ("is not".to_string(), "secret".to_string()),
42        ("but adds".to_string(), "useful metadata".to_string()),
43        (
44            "that can help you".to_string(),
45            "be confident that".to_string(),
46        ),
47        (
48            "the data you are handling".to_string(),
49            "is what you think it is".to_string(),
50        ),
51    ]);
52
53    // 4. Create a custom SigningSuiteOnlyCMM
54    let mpl_config = MaterialProvidersConfig::builder().build()?;
55    let mpl = mpl_client::Client::from_conf(mpl_config)?;
56
57    let kms_keyring = mpl
58        .create_aws_kms_keyring()
59        .kms_key_id(kms_key_id)
60        .kms_client(kms_client)
61        .send()
62        .await?;
63
64    let signing_suite_only_cmm = SigningSuiteOnlyCMM::new(kms_keyring);
65
66    let signing_suite_only_cmm_ref: CryptographicMaterialsManagerRef =
67        CryptographicMaterialsManagerRef {
68            inner: ::std::sync::Arc::new(std::sync::Mutex::new(signing_suite_only_cmm)),
69        };
70
71    // 5. Encrypt the data with the encryption_context
72    let plaintext = example_data.as_bytes();
73
74    let encryption_response = esdk_client
75        .encrypt()
76        .plaintext(plaintext)
77        .materials_manager(signing_suite_only_cmm_ref.clone())
78        .encryption_context(encryption_context.clone())
79        .algorithm_suite_id(EsdkAlgorithmSuiteId::AlgAes256GcmHkdfSha512CommitKeyEcdsaP384)
80        .send()
81        .await?;
82
83    let ciphertext = encryption_response
84        .ciphertext
85        .expect("Unable to unwrap ciphertext from encryption response");
86
87    // 6. Demonstrate that the ciphertext and plaintext are different.
88    // (This is an example for demonstration; you do not need to do this in your own code.)
89    assert_ne!(
90        ciphertext,
91        aws_smithy_types::Blob::new(plaintext),
92        "Ciphertext and plaintext data are the same. Invalid encryption"
93    );
94
95    // 7. Decrypt your encrypted data using the same keyring you used on encrypt.
96    let decryption_response = esdk_client
97        .decrypt()
98        .ciphertext(ciphertext)
99        .materials_manager(signing_suite_only_cmm_ref.clone())
100        // Provide the encryption context that was supplied to the encrypt method
101        .encryption_context(encryption_context.clone())
102        .send()
103        .await?;
104
105    let decrypted_plaintext = decryption_response
106        .plaintext
107        .expect("Unable to unwrap plaintext from decryption response");
108
109    // 8. Demonstrate that the decrypted plaintext is identical to the original plaintext.
110    // (This is an example for demonstration; you do not need to do this in your own code.)
111    assert_eq!(
112        decrypted_plaintext,
113        aws_smithy_types::Blob::new(plaintext),
114        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
115    );
116
117    // 9. Demonstrate that a Non Signing Algorithm Suite will be rejected
118    // by the CMM.
119    let encryption_response_non_signing = esdk_client
120        .encrypt()
121        .plaintext(plaintext)
122        .materials_manager(signing_suite_only_cmm_ref)
123        .encryption_context(encryption_context.clone())
124        .algorithm_suite_id(EsdkAlgorithmSuiteId::AlgAes256GcmHkdfSha512CommitKey)
125        .send()
126        .await;
127
128    match encryption_response_non_signing {
129        Ok(_) => panic!(
130            "Encrypt using non signing algorithm suite MUST \
131                            raise AwsCryptographicMaterialProvidersError"
132        ),
133        Err(AwsCryptographicMaterialProvidersError { error: _e }) => (),
134        _ => panic!("Unexpected error type"),
135    }
136
137    println!("SigningSuiteOnlyCMM Example Completed Successfully");
138
139    Ok(())
140}
More examples
Hide additional examples
examples/cryptographic_materials_manager/required_encryption_context/required_encryption_context_example.rs (line 117)
19pub async fn encrypt_and_decrypt_with_cmm(
20    example_data: &str,
21    kms_key_id: &str,
22) -> Result<(), crate::BoxError> {
23    // 1. Instantiate the encryption SDK client.
24    // This builds the default client with the RequireEncryptRequireDecrypt commitment policy,
25    // which enforces that this client only encrypts using committing algorithm suites and enforces
26    // that this client will only decrypt encrypted messages that were created with a committing
27    // algorithm suite.
28    let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
29    let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
30
31    // 2. Create a KMS client.
32    let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
33    let kms_client = aws_sdk_kms::Client::new(&sdk_config);
34
35    // 3. Create encryption context.
36    // Remember that your encryption context is NOT SECRET.
37    // For more information, see
38    // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context
39    let encryption_context = HashMap::from([
40        ("encryption".to_string(), "context".to_string()),
41        ("is not".to_string(), "secret".to_string()),
42        ("but adds".to_string(), "useful metadata".to_string()),
43        (
44            "that can help you".to_string(),
45            "be confident that".to_string(),
46        ),
47        (
48            "the data you are handling".to_string(),
49            "is what you think it is".to_string(),
50        ),
51        ("requiredKey1".to_string(), "requiredValue1".to_string()),
52        ("requiredKey2".to_string(), "requiredValue2".to_string()),
53    ]);
54
55    // 4. Create your required encryption context keys.
56    // These keys MUST be in your encryption context.
57    // These keys and their corresponding values WILL NOT be stored on the message but will be used
58    // for authentication.
59    let required_encryption_context_keys: Vec<String> =
60        vec!["requiredKey1".to_string(), "requiredKey2".to_string()];
61
62    // 5. Create a KMS keyring
63    let mpl_config = MaterialProvidersConfig::builder().build()?;
64    let mpl = mpl_client::Client::from_conf(mpl_config)?;
65
66    let kms_keyring = mpl
67        .create_aws_kms_keyring()
68        .kms_key_id(kms_key_id)
69        .kms_client(kms_client)
70        .send()
71        .await?;
72
73    // 6. Create the required encryption context CMM.
74    let underlying_cmm = mpl
75        .create_default_cryptographic_materials_manager()
76        .keyring(kms_keyring)
77        .send()
78        .await?;
79
80    let required_ec_cmm = mpl
81        .create_required_encryption_context_cmm()
82        .underlying_cmm(underlying_cmm.clone())
83        .required_encryption_context_keys(required_encryption_context_keys)
84        .send()
85        .await?;
86
87    // 7. Encrypt the data with the encryption_context
88    // NOTE: the keys "requiredKey1", and "requiredKey2"
89    // WILL NOT be stored in the message header, but "encryption", "is not",
90    // "but adds", "that can help you", and "the data you are handling" WILL be stored.
91    let plaintext = example_data.as_bytes();
92
93    let encryption_response = esdk_client
94        .encrypt()
95        .plaintext(plaintext)
96        .materials_manager(required_ec_cmm.clone())
97        .encryption_context(encryption_context.clone())
98        .send()
99        .await?;
100
101    let ciphertext = encryption_response
102        .ciphertext
103        .expect("Unable to unwrap ciphertext from encryption response");
104
105    // 8. Demonstrate that the ciphertext and plaintext are different.
106    // (This is an example for demonstration; you do not need to do this in your own code.)
107    assert_ne!(
108        ciphertext,
109        aws_smithy_types::Blob::new(plaintext),
110        "Ciphertext and plaintext data are the same. Invalid encryption"
111    );
112
113    // 9. Decrypt your encrypted data using the same keyring you used on encrypt.
114    let decryption_response = esdk_client
115        .decrypt()
116        .ciphertext(ciphertext.clone())
117        .materials_manager(required_ec_cmm.clone())
118        // Provide the encryption context that was supplied to the encrypt method
119        .encryption_context(encryption_context.clone())
120        .send()
121        .await?;
122
123    let decrypted_plaintext = decryption_response
124        .plaintext
125        .expect("Unable to unwrap plaintext from decryption response");
126
127    // 10. Demonstrate that the decrypted plaintext is identical to the original plaintext.
128    // (This is an example for demonstration; you do not need to do this in your own code.)
129    assert_eq!(
130        decrypted_plaintext,
131        aws_smithy_types::Blob::new(plaintext),
132        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
133    );
134
135    // 11. Attempt to decrypt your encrypted data using the same cryptographic material manager
136    // you used on encrypt, but we won't pass the encryption context we DID NOT store on the message.
137    // This will fail
138    let decryption_response_without_ec = esdk_client
139        .decrypt()
140        .ciphertext(ciphertext.clone())
141        .materials_manager(required_ec_cmm.clone())
142        .send()
143        .await;
144
145    match decryption_response_without_ec {
146        Ok(_) => panic!(
147            "Decrypt without encryption context MUST \
148                            raise AwsCryptographicMaterialProvidersError"
149        ),
150        Err(AwsCryptographicMaterialProvidersError { error: _e }) => (),
151        _ => panic!("Unexpected error type"),
152    }
153
154    // 12. Decrypt your encrypted data using the same cryptographic material manager
155    // you used to encrypt, but supply encryption context that contains ONLY the encryption context that
156    // was NOT stored. This will pass.
157    let reproduced_encryption_context = HashMap::from([
158        ("requiredKey1".to_string(), "requiredValue1".to_string()),
159        ("requiredKey2".to_string(), "requiredValue2".to_string()),
160    ]);
161
162    let decryption_response_with_reproduced_ec = esdk_client
163        .decrypt()
164        .ciphertext(ciphertext.clone())
165        .materials_manager(required_ec_cmm)
166        // Provide the encryption context that was supplied to the encrypt method
167        .encryption_context(reproduced_encryption_context)
168        .send()
169        .await?;
170
171    let decrypted_plaintext_with_reproduced_ec = decryption_response_with_reproduced_ec
172        .plaintext
173        .expect("Unable to unwrap plaintext from decryption response");
174
175    // Demonstrate that the decrypted plaintext is identical to the original plaintext.
176    // (This is an example for demonstration; you do not need to do this in your own code.)
177    assert_eq!(
178        decrypted_plaintext_with_reproduced_ec,
179        aws_smithy_types::Blob::new(plaintext),
180        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
181    );
182
183    // 13. You can decrypt the ciphertext using the underlying cmm, but not providing the
184    // encryption context with the request will result in an AwsCryptographicMaterialProvidersError
185
186    // This will pass
187    let decryption_response_with_ec_underlying_cmm = esdk_client
188        .decrypt()
189        .ciphertext(ciphertext.clone())
190        .materials_manager(underlying_cmm.clone())
191        // Provide the encryption context that was supplied to the encrypt method
192        .encryption_context(encryption_context)
193        .send()
194        .await?;
195
196    let decrypted_plaintext_with_ec_underlying_cmm = decryption_response_with_ec_underlying_cmm
197        .plaintext
198        .expect("Unable to unwrap plaintext from decryption response");
199
200    // Demonstrate that the decrypted plaintext is identical to the original plaintext.
201    // (This is an example for demonstration; you do not need to do this in your own code.)
202    assert_eq!(
203        decrypted_plaintext_with_ec_underlying_cmm,
204        aws_smithy_types::Blob::new(plaintext),
205        "Decrypted plaintext should be identical to the original plaintext. Invalid decryption"
206    );
207
208    // This will fail
209    let decryption_response_without_ec_underlying_cmm = esdk_client
210        .decrypt()
211        .ciphertext(ciphertext)
212        .materials_manager(underlying_cmm)
213        .send()
214        .await;
215
216    match decryption_response_without_ec_underlying_cmm {
217        Ok(_) => panic!(
218            "Decrypt without encryption context MUST \
219                            raise AwsCryptographicMaterialProvidersError"
220        ),
221        Err(AwsCryptographicMaterialProvidersError { error: _e }) => (),
222        _ => panic!("Unexpected error type"),
223    }
224
225    println!("Required Encryption Context CMM Example Completed Successfully");
226
227    Ok(())
228}
Source

pub fn set_materials_manager( self, input: Option<CryptographicMaterialsManagerRef>, ) -> Self

Source

pub fn get_materials_manager(&self) -> &Option<CryptographicMaterialsManagerRef>

Trait Implementations§

Source§

impl Clone for DecryptFluentBuilder

Source§

fn clone(&self) -> DecryptFluentBuilder

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DecryptFluentBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AnyRef for T
where T: 'static,

Source§

fn as_any_ref(&self) -> &(dyn Any + 'static)

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T
where T: ?Sized,

Source§

fn upcast(&self) -> Ptr<T>

Source§

impl<T> UpcastObject<T> for T
where T: ?Sized,

Source§

fn upcast(&self) -> Object<T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more