Skip to main content

EncryptFluentBuilder

Struct EncryptFluentBuilder 

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

Fluent builder constructing a request to Encrypt.

Implementations§

Source§

impl EncryptFluentBuilder

Source

pub fn as_input(&self) -> &EncryptInputBuilder

Access the Encrypt as a reference.

Source

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

Sends the request and returns the response.

Examples found in repository?
examples/keyring/ecdh/kms_ecdh_discovery_keyring_example.rs (line 206)
157async fn get_ciphertext(
158    example_data: &str,
159    encryption_context: HashMap<String, String>,
160    ecc_recipient_key_arn: &str,
161    ecdh_curve_spec: EcdhCurveSpec,
162    kms_client: aws_sdk_kms::Client,
163    esdk_client: esdk_client::Client,
164) -> Result<Blob, crate::BoxError> {
165    // 1. Create the public keys for sender and recipient
166    // Recipient keys are taken as input for this example
167    // Sender ECC key used in this example is TEST_KMS_ECDH_KEY_ID_P256_SENDER
168    let public_key_sender_utf8_bytes =
169        generate_kms_ecc_public_key(TEST_KMS_ECDH_KEY_ID_P256_SENDER).await?;
170    let public_key_recipient_utf8_bytes =
171        generate_kms_ecc_public_key(ecc_recipient_key_arn).await?;
172
173    // 2. Create the KmsPrivateKeyToStaticPublicKeyInput
174    let kms_ecdh_static_configuration_input = KmsPrivateKeyToStaticPublicKeyInput::builder()
175        .sender_kms_identifier(TEST_KMS_ECDH_KEY_ID_P256_SENDER)
176        // Must be a UTF8 DER-encoded X.509 public key
177        .sender_public_key(public_key_sender_utf8_bytes)
178        // Must be a UTF8 DER-encoded X.509 public key
179        .recipient_public_key(public_key_recipient_utf8_bytes)
180        .build()?;
181
182    let kms_ecdh_static_configuration = KmsEcdhStaticConfigurations::KmsPrivateKeyToStaticPublicKey(
183        kms_ecdh_static_configuration_input,
184    );
185
186    // 3. Create the KMS ECDH keyring.
187    let mpl_config = MaterialProvidersConfig::builder().build()?;
188    let mpl = mpl_client::Client::from_conf(mpl_config)?;
189
190    let kms_ecdh_keyring = mpl
191        .create_aws_kms_ecdh_keyring()
192        .kms_client(kms_client)
193        .curve_spec(ecdh_curve_spec)
194        .key_agreement_scheme(kms_ecdh_static_configuration)
195        .send()
196        .await?;
197
198    // 4. Encrypt the data with the encryption_context
199    let plaintext = example_data.as_bytes();
200
201    let encryption_response = esdk_client
202        .encrypt()
203        .plaintext(plaintext)
204        .keyring(kms_ecdh_keyring.clone())
205        .encryption_context(encryption_context.clone())
206        .send()
207        .await?;
208
209    let ciphertext = encryption_response
210        .ciphertext
211        .expect("Unable to unwrap ciphertext from encryption response");
212
213    // 5. Demonstrate that the ciphertext and plaintext are different.
214    // (This is an example for demonstration; you do not need to do this in your own code.)
215    assert_ne!(
216        ciphertext,
217        aws_smithy_types::Blob::new(plaintext),
218        "Ciphertext and plaintext data are the same. Invalid encryption"
219    );
220
221    Ok(ciphertext)
222}
More examples
Hide additional examples
examples/keyring/ecdh/public_key_discovery_raw_ecdh_keyring_example.rs (line 254)
202async fn get_ciphertext(
203    example_data: &str,
204    ecdh_curve_spec: EcdhCurveSpec,
205    encryption_context: HashMap<String, String>,
206    esdk_client: esdk_client::Client,
207    mpl: mpl_client::Client,
208) -> Result<Blob, crate::BoxError> {
209    // 1. Load keys from UTF-8 encoded PEM files.
210
211    // Load public key from UTF-8 encoded PEM files into a DER encoded public key.
212    let public_key_file_content =
213        std::fs::read_to_string(Path::new(EXAMPLE_ECC_PUBLIC_KEY_FILENAME_RECIPIENT))?;
214    let parsed_public_key_file_content = parse(public_key_file_content)?;
215    let public_key_recipient_utf8_bytes = parsed_public_key_file_content.contents();
216
217    // 2. Create the EphemeralPrivateKeyToStaticPublicKeyInput to generate the ciphertext
218    let ephemeral_raw_ecdh_static_configuration_input =
219        EphemeralPrivateKeyToStaticPublicKeyInput::builder()
220            // Must be a UTF8 DER-encoded X.509 public key
221            .recipient_public_key(public_key_recipient_utf8_bytes)
222            .build()?;
223
224    let ephemeral_raw_ecdh_static_configuration =
225        RawEcdhStaticConfigurations::EphemeralPrivateKeyToStaticPublicKey(
226            ephemeral_raw_ecdh_static_configuration_input,
227        );
228
229    // 3. Create the Ephemeral Raw ECDH keyring.
230
231    // Create the keyring.
232    // This keyring uses an ephemeral configuration. This configuration will always create a new
233    // key pair as the sender key pair for the key agreement operation. The ephemeral configuration can only
234    // encrypt data and CANNOT decrypt messages.
235    let ephemeral_raw_ecdh_keyring = mpl
236        .create_raw_ecdh_keyring()
237        .curve_spec(ecdh_curve_spec)
238        .key_agreement_scheme(ephemeral_raw_ecdh_static_configuration)
239        .send()
240        .await?;
241
242    // 4. Encrypt the data with the encryption_context
243
244    // A raw ecdh keyring with Ephemeral configuration cannot decrypt data since the key pair
245    // used as the sender is ephemeral. This means that at decrypt time it does not have
246    // the private key that corresponds to the public key that is stored on the message.
247    let plaintext = example_data.as_bytes();
248
249    let encryption_response = esdk_client
250        .encrypt()
251        .plaintext(plaintext)
252        .keyring(ephemeral_raw_ecdh_keyring)
253        .encryption_context(encryption_context)
254        .send()
255        .await?;
256
257    let ciphertext = encryption_response
258        .ciphertext
259        .expect("Unable to unwrap ciphertext from encryption response");
260
261    // 5. Demonstrate that the ciphertext and plaintext are different.
262    // (This is an example for demonstration; you do not need to do this in your own code.)
263    assert_ne!(
264        ciphertext,
265        aws_smithy_types::Blob::new(plaintext),
266        "Ciphertext and plaintext data are the same. Invalid encryption"
267    );
268
269    Ok(ciphertext)
270}
examples/keyring/aws_kms_keyring_example.rs (line 83)
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}
examples/keyring/aws_kms_rsa_keyring_example.rs (line 87)
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 94)
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 115)
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}
Source

pub fn algorithm_suite_id(self, input: impl Into<EsdkAlgorithmSuiteId>) -> Self

Examples found in repository?
examples/keyring/aws_kms_rsa_keyring_example.rs (line 86)
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}
More examples
Hide additional examples
examples/set_encryption_algorithm_suite_example.rs (line 114)
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/cryptographic_materials_manager/restrict_algorithm_suite/signing_only_example.rs (line 79)
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}
Source

pub fn set_algorithm_suite_id(self, input: Option<EsdkAlgorithmSuiteId>) -> Self

Source

pub fn get_algorithm_suite_id(&self) -> &Option<EsdkAlgorithmSuiteId>

Source

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

Examples found in repository?
examples/keyring/ecdh/kms_ecdh_discovery_keyring_example.rs (line 205)
157async fn get_ciphertext(
158    example_data: &str,
159    encryption_context: HashMap<String, String>,
160    ecc_recipient_key_arn: &str,
161    ecdh_curve_spec: EcdhCurveSpec,
162    kms_client: aws_sdk_kms::Client,
163    esdk_client: esdk_client::Client,
164) -> Result<Blob, crate::BoxError> {
165    // 1. Create the public keys for sender and recipient
166    // Recipient keys are taken as input for this example
167    // Sender ECC key used in this example is TEST_KMS_ECDH_KEY_ID_P256_SENDER
168    let public_key_sender_utf8_bytes =
169        generate_kms_ecc_public_key(TEST_KMS_ECDH_KEY_ID_P256_SENDER).await?;
170    let public_key_recipient_utf8_bytes =
171        generate_kms_ecc_public_key(ecc_recipient_key_arn).await?;
172
173    // 2. Create the KmsPrivateKeyToStaticPublicKeyInput
174    let kms_ecdh_static_configuration_input = KmsPrivateKeyToStaticPublicKeyInput::builder()
175        .sender_kms_identifier(TEST_KMS_ECDH_KEY_ID_P256_SENDER)
176        // Must be a UTF8 DER-encoded X.509 public key
177        .sender_public_key(public_key_sender_utf8_bytes)
178        // Must be a UTF8 DER-encoded X.509 public key
179        .recipient_public_key(public_key_recipient_utf8_bytes)
180        .build()?;
181
182    let kms_ecdh_static_configuration = KmsEcdhStaticConfigurations::KmsPrivateKeyToStaticPublicKey(
183        kms_ecdh_static_configuration_input,
184    );
185
186    // 3. Create the KMS ECDH keyring.
187    let mpl_config = MaterialProvidersConfig::builder().build()?;
188    let mpl = mpl_client::Client::from_conf(mpl_config)?;
189
190    let kms_ecdh_keyring = mpl
191        .create_aws_kms_ecdh_keyring()
192        .kms_client(kms_client)
193        .curve_spec(ecdh_curve_spec)
194        .key_agreement_scheme(kms_ecdh_static_configuration)
195        .send()
196        .await?;
197
198    // 4. Encrypt the data with the encryption_context
199    let plaintext = example_data.as_bytes();
200
201    let encryption_response = esdk_client
202        .encrypt()
203        .plaintext(plaintext)
204        .keyring(kms_ecdh_keyring.clone())
205        .encryption_context(encryption_context.clone())
206        .send()
207        .await?;
208
209    let ciphertext = encryption_response
210        .ciphertext
211        .expect("Unable to unwrap ciphertext from encryption response");
212
213    // 5. Demonstrate that the ciphertext and plaintext are different.
214    // (This is an example for demonstration; you do not need to do this in your own code.)
215    assert_ne!(
216        ciphertext,
217        aws_smithy_types::Blob::new(plaintext),
218        "Ciphertext and plaintext data are the same. Invalid encryption"
219    );
220
221    Ok(ciphertext)
222}
More examples
Hide additional examples
examples/keyring/ecdh/public_key_discovery_raw_ecdh_keyring_example.rs (line 253)
202async fn get_ciphertext(
203    example_data: &str,
204    ecdh_curve_spec: EcdhCurveSpec,
205    encryption_context: HashMap<String, String>,
206    esdk_client: esdk_client::Client,
207    mpl: mpl_client::Client,
208) -> Result<Blob, crate::BoxError> {
209    // 1. Load keys from UTF-8 encoded PEM files.
210
211    // Load public key from UTF-8 encoded PEM files into a DER encoded public key.
212    let public_key_file_content =
213        std::fs::read_to_string(Path::new(EXAMPLE_ECC_PUBLIC_KEY_FILENAME_RECIPIENT))?;
214    let parsed_public_key_file_content = parse(public_key_file_content)?;
215    let public_key_recipient_utf8_bytes = parsed_public_key_file_content.contents();
216
217    // 2. Create the EphemeralPrivateKeyToStaticPublicKeyInput to generate the ciphertext
218    let ephemeral_raw_ecdh_static_configuration_input =
219        EphemeralPrivateKeyToStaticPublicKeyInput::builder()
220            // Must be a UTF8 DER-encoded X.509 public key
221            .recipient_public_key(public_key_recipient_utf8_bytes)
222            .build()?;
223
224    let ephemeral_raw_ecdh_static_configuration =
225        RawEcdhStaticConfigurations::EphemeralPrivateKeyToStaticPublicKey(
226            ephemeral_raw_ecdh_static_configuration_input,
227        );
228
229    // 3. Create the Ephemeral Raw ECDH keyring.
230
231    // Create the keyring.
232    // This keyring uses an ephemeral configuration. This configuration will always create a new
233    // key pair as the sender key pair for the key agreement operation. The ephemeral configuration can only
234    // encrypt data and CANNOT decrypt messages.
235    let ephemeral_raw_ecdh_keyring = mpl
236        .create_raw_ecdh_keyring()
237        .curve_spec(ecdh_curve_spec)
238        .key_agreement_scheme(ephemeral_raw_ecdh_static_configuration)
239        .send()
240        .await?;
241
242    // 4. Encrypt the data with the encryption_context
243
244    // A raw ecdh keyring with Ephemeral configuration cannot decrypt data since the key pair
245    // used as the sender is ephemeral. This means that at decrypt time it does not have
246    // the private key that corresponds to the public key that is stored on the message.
247    let plaintext = example_data.as_bytes();
248
249    let encryption_response = esdk_client
250        .encrypt()
251        .plaintext(plaintext)
252        .keyring(ephemeral_raw_ecdh_keyring)
253        .encryption_context(encryption_context)
254        .send()
255        .await?;
256
257    let ciphertext = encryption_response
258        .ciphertext
259        .expect("Unable to unwrap ciphertext from encryption response");
260
261    // 5. Demonstrate that the ciphertext and plaintext are different.
262    // (This is an example for demonstration; you do not need to do this in your own code.)
263    assert_ne!(
264        ciphertext,
265        aws_smithy_types::Blob::new(plaintext),
266        "Ciphertext and plaintext data are the same. Invalid encryption"
267    );
268
269    Ok(ciphertext)
270}
examples/keyring/aws_kms_keyring_example.rs (line 82)
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}
examples/keyring/aws_kms_rsa_keyring_example.rs (line 85)
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 93)
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 113)
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}
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 frame_length(self, input: impl Into<i64>) -> Self

Source

pub fn set_frame_length(self, input: Option<i64>) -> Self

Source

pub fn get_frame_length(&self) -> &Option<i64>

Source

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

Examples found in repository?
examples/keyring/ecdh/kms_ecdh_discovery_keyring_example.rs (line 204)
157async fn get_ciphertext(
158    example_data: &str,
159    encryption_context: HashMap<String, String>,
160    ecc_recipient_key_arn: &str,
161    ecdh_curve_spec: EcdhCurveSpec,
162    kms_client: aws_sdk_kms::Client,
163    esdk_client: esdk_client::Client,
164) -> Result<Blob, crate::BoxError> {
165    // 1. Create the public keys for sender and recipient
166    // Recipient keys are taken as input for this example
167    // Sender ECC key used in this example is TEST_KMS_ECDH_KEY_ID_P256_SENDER
168    let public_key_sender_utf8_bytes =
169        generate_kms_ecc_public_key(TEST_KMS_ECDH_KEY_ID_P256_SENDER).await?;
170    let public_key_recipient_utf8_bytes =
171        generate_kms_ecc_public_key(ecc_recipient_key_arn).await?;
172
173    // 2. Create the KmsPrivateKeyToStaticPublicKeyInput
174    let kms_ecdh_static_configuration_input = KmsPrivateKeyToStaticPublicKeyInput::builder()
175        .sender_kms_identifier(TEST_KMS_ECDH_KEY_ID_P256_SENDER)
176        // Must be a UTF8 DER-encoded X.509 public key
177        .sender_public_key(public_key_sender_utf8_bytes)
178        // Must be a UTF8 DER-encoded X.509 public key
179        .recipient_public_key(public_key_recipient_utf8_bytes)
180        .build()?;
181
182    let kms_ecdh_static_configuration = KmsEcdhStaticConfigurations::KmsPrivateKeyToStaticPublicKey(
183        kms_ecdh_static_configuration_input,
184    );
185
186    // 3. Create the KMS ECDH keyring.
187    let mpl_config = MaterialProvidersConfig::builder().build()?;
188    let mpl = mpl_client::Client::from_conf(mpl_config)?;
189
190    let kms_ecdh_keyring = mpl
191        .create_aws_kms_ecdh_keyring()
192        .kms_client(kms_client)
193        .curve_spec(ecdh_curve_spec)
194        .key_agreement_scheme(kms_ecdh_static_configuration)
195        .send()
196        .await?;
197
198    // 4. Encrypt the data with the encryption_context
199    let plaintext = example_data.as_bytes();
200
201    let encryption_response = esdk_client
202        .encrypt()
203        .plaintext(plaintext)
204        .keyring(kms_ecdh_keyring.clone())
205        .encryption_context(encryption_context.clone())
206        .send()
207        .await?;
208
209    let ciphertext = encryption_response
210        .ciphertext
211        .expect("Unable to unwrap ciphertext from encryption response");
212
213    // 5. Demonstrate that the ciphertext and plaintext are different.
214    // (This is an example for demonstration; you do not need to do this in your own code.)
215    assert_ne!(
216        ciphertext,
217        aws_smithy_types::Blob::new(plaintext),
218        "Ciphertext and plaintext data are the same. Invalid encryption"
219    );
220
221    Ok(ciphertext)
222}
More examples
Hide additional examples
examples/keyring/ecdh/public_key_discovery_raw_ecdh_keyring_example.rs (line 252)
202async fn get_ciphertext(
203    example_data: &str,
204    ecdh_curve_spec: EcdhCurveSpec,
205    encryption_context: HashMap<String, String>,
206    esdk_client: esdk_client::Client,
207    mpl: mpl_client::Client,
208) -> Result<Blob, crate::BoxError> {
209    // 1. Load keys from UTF-8 encoded PEM files.
210
211    // Load public key from UTF-8 encoded PEM files into a DER encoded public key.
212    let public_key_file_content =
213        std::fs::read_to_string(Path::new(EXAMPLE_ECC_PUBLIC_KEY_FILENAME_RECIPIENT))?;
214    let parsed_public_key_file_content = parse(public_key_file_content)?;
215    let public_key_recipient_utf8_bytes = parsed_public_key_file_content.contents();
216
217    // 2. Create the EphemeralPrivateKeyToStaticPublicKeyInput to generate the ciphertext
218    let ephemeral_raw_ecdh_static_configuration_input =
219        EphemeralPrivateKeyToStaticPublicKeyInput::builder()
220            // Must be a UTF8 DER-encoded X.509 public key
221            .recipient_public_key(public_key_recipient_utf8_bytes)
222            .build()?;
223
224    let ephemeral_raw_ecdh_static_configuration =
225        RawEcdhStaticConfigurations::EphemeralPrivateKeyToStaticPublicKey(
226            ephemeral_raw_ecdh_static_configuration_input,
227        );
228
229    // 3. Create the Ephemeral Raw ECDH keyring.
230
231    // Create the keyring.
232    // This keyring uses an ephemeral configuration. This configuration will always create a new
233    // key pair as the sender key pair for the key agreement operation. The ephemeral configuration can only
234    // encrypt data and CANNOT decrypt messages.
235    let ephemeral_raw_ecdh_keyring = mpl
236        .create_raw_ecdh_keyring()
237        .curve_spec(ecdh_curve_spec)
238        .key_agreement_scheme(ephemeral_raw_ecdh_static_configuration)
239        .send()
240        .await?;
241
242    // 4. Encrypt the data with the encryption_context
243
244    // A raw ecdh keyring with Ephemeral configuration cannot decrypt data since the key pair
245    // used as the sender is ephemeral. This means that at decrypt time it does not have
246    // the private key that corresponds to the public key that is stored on the message.
247    let plaintext = example_data.as_bytes();
248
249    let encryption_response = esdk_client
250        .encrypt()
251        .plaintext(plaintext)
252        .keyring(ephemeral_raw_ecdh_keyring)
253        .encryption_context(encryption_context)
254        .send()
255        .await?;
256
257    let ciphertext = encryption_response
258        .ciphertext
259        .expect("Unable to unwrap ciphertext from encryption response");
260
261    // 5. Demonstrate that the ciphertext and plaintext are different.
262    // (This is an example for demonstration; you do not need to do this in your own code.)
263    assert_ne!(
264        ciphertext,
265        aws_smithy_types::Blob::new(plaintext),
266        "Ciphertext and plaintext data are the same. Invalid encryption"
267    );
268
269    Ok(ciphertext)
270}
examples/keyring/aws_kms_keyring_example.rs (line 81)
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}
examples/keyring/aws_kms_rsa_keyring_example.rs (line 84)
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 92)
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 112)
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}
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 77)
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 96)
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>

Source

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

Examples found in repository?
examples/keyring/ecdh/kms_ecdh_discovery_keyring_example.rs (line 203)
157async fn get_ciphertext(
158    example_data: &str,
159    encryption_context: HashMap<String, String>,
160    ecc_recipient_key_arn: &str,
161    ecdh_curve_spec: EcdhCurveSpec,
162    kms_client: aws_sdk_kms::Client,
163    esdk_client: esdk_client::Client,
164) -> Result<Blob, crate::BoxError> {
165    // 1. Create the public keys for sender and recipient
166    // Recipient keys are taken as input for this example
167    // Sender ECC key used in this example is TEST_KMS_ECDH_KEY_ID_P256_SENDER
168    let public_key_sender_utf8_bytes =
169        generate_kms_ecc_public_key(TEST_KMS_ECDH_KEY_ID_P256_SENDER).await?;
170    let public_key_recipient_utf8_bytes =
171        generate_kms_ecc_public_key(ecc_recipient_key_arn).await?;
172
173    // 2. Create the KmsPrivateKeyToStaticPublicKeyInput
174    let kms_ecdh_static_configuration_input = KmsPrivateKeyToStaticPublicKeyInput::builder()
175        .sender_kms_identifier(TEST_KMS_ECDH_KEY_ID_P256_SENDER)
176        // Must be a UTF8 DER-encoded X.509 public key
177        .sender_public_key(public_key_sender_utf8_bytes)
178        // Must be a UTF8 DER-encoded X.509 public key
179        .recipient_public_key(public_key_recipient_utf8_bytes)
180        .build()?;
181
182    let kms_ecdh_static_configuration = KmsEcdhStaticConfigurations::KmsPrivateKeyToStaticPublicKey(
183        kms_ecdh_static_configuration_input,
184    );
185
186    // 3. Create the KMS ECDH keyring.
187    let mpl_config = MaterialProvidersConfig::builder().build()?;
188    let mpl = mpl_client::Client::from_conf(mpl_config)?;
189
190    let kms_ecdh_keyring = mpl
191        .create_aws_kms_ecdh_keyring()
192        .kms_client(kms_client)
193        .curve_spec(ecdh_curve_spec)
194        .key_agreement_scheme(kms_ecdh_static_configuration)
195        .send()
196        .await?;
197
198    // 4. Encrypt the data with the encryption_context
199    let plaintext = example_data.as_bytes();
200
201    let encryption_response = esdk_client
202        .encrypt()
203        .plaintext(plaintext)
204        .keyring(kms_ecdh_keyring.clone())
205        .encryption_context(encryption_context.clone())
206        .send()
207        .await?;
208
209    let ciphertext = encryption_response
210        .ciphertext
211        .expect("Unable to unwrap ciphertext from encryption response");
212
213    // 5. Demonstrate that the ciphertext and plaintext are different.
214    // (This is an example for demonstration; you do not need to do this in your own code.)
215    assert_ne!(
216        ciphertext,
217        aws_smithy_types::Blob::new(plaintext),
218        "Ciphertext and plaintext data are the same. Invalid encryption"
219    );
220
221    Ok(ciphertext)
222}
More examples
Hide additional examples
examples/keyring/ecdh/public_key_discovery_raw_ecdh_keyring_example.rs (line 251)
202async fn get_ciphertext(
203    example_data: &str,
204    ecdh_curve_spec: EcdhCurveSpec,
205    encryption_context: HashMap<String, String>,
206    esdk_client: esdk_client::Client,
207    mpl: mpl_client::Client,
208) -> Result<Blob, crate::BoxError> {
209    // 1. Load keys from UTF-8 encoded PEM files.
210
211    // Load public key from UTF-8 encoded PEM files into a DER encoded public key.
212    let public_key_file_content =
213        std::fs::read_to_string(Path::new(EXAMPLE_ECC_PUBLIC_KEY_FILENAME_RECIPIENT))?;
214    let parsed_public_key_file_content = parse(public_key_file_content)?;
215    let public_key_recipient_utf8_bytes = parsed_public_key_file_content.contents();
216
217    // 2. Create the EphemeralPrivateKeyToStaticPublicKeyInput to generate the ciphertext
218    let ephemeral_raw_ecdh_static_configuration_input =
219        EphemeralPrivateKeyToStaticPublicKeyInput::builder()
220            // Must be a UTF8 DER-encoded X.509 public key
221            .recipient_public_key(public_key_recipient_utf8_bytes)
222            .build()?;
223
224    let ephemeral_raw_ecdh_static_configuration =
225        RawEcdhStaticConfigurations::EphemeralPrivateKeyToStaticPublicKey(
226            ephemeral_raw_ecdh_static_configuration_input,
227        );
228
229    // 3. Create the Ephemeral Raw ECDH keyring.
230
231    // Create the keyring.
232    // This keyring uses an ephemeral configuration. This configuration will always create a new
233    // key pair as the sender key pair for the key agreement operation. The ephemeral configuration can only
234    // encrypt data and CANNOT decrypt messages.
235    let ephemeral_raw_ecdh_keyring = mpl
236        .create_raw_ecdh_keyring()
237        .curve_spec(ecdh_curve_spec)
238        .key_agreement_scheme(ephemeral_raw_ecdh_static_configuration)
239        .send()
240        .await?;
241
242    // 4. Encrypt the data with the encryption_context
243
244    // A raw ecdh keyring with Ephemeral configuration cannot decrypt data since the key pair
245    // used as the sender is ephemeral. This means that at decrypt time it does not have
246    // the private key that corresponds to the public key that is stored on the message.
247    let plaintext = example_data.as_bytes();
248
249    let encryption_response = esdk_client
250        .encrypt()
251        .plaintext(plaintext)
252        .keyring(ephemeral_raw_ecdh_keyring)
253        .encryption_context(encryption_context)
254        .send()
255        .await?;
256
257    let ciphertext = encryption_response
258        .ciphertext
259        .expect("Unable to unwrap ciphertext from encryption response");
260
261    // 5. Demonstrate that the ciphertext and plaintext are different.
262    // (This is an example for demonstration; you do not need to do this in your own code.)
263    assert_ne!(
264        ciphertext,
265        aws_smithy_types::Blob::new(plaintext),
266        "Ciphertext and plaintext data are the same. Invalid encryption"
267    );
268
269    Ok(ciphertext)
270}
examples/keyring/aws_kms_keyring_example.rs (line 80)
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}
examples/keyring/aws_kms_rsa_keyring_example.rs (line 83)
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 91)
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 111)
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}
Source

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

Source

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

Trait Implementations§

Source§

impl Clone for EncryptFluentBuilder

Source§

fn clone(&self) -> EncryptFluentBuilder

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 EncryptFluentBuilder

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