### Encryptor Example Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aead-stream.md Example demonstrating how to obtain a stateful encryptor from a StreamPrimitive. Requires a key and nonce for initialization. ```rust let primitive = StreamPrimitive::new(&key, &nonce); let mut encryptor = primitive.encryptor(); ``` -------------------------------- ### SivAead Constructor Example Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Demonstrates how to create a new SIV-AEAD cipher instance using the `new` constructor. This example initializes an Aes256SivAead cipher with a 64-byte key. ```rust use aes_siv::{Aes256SivAead, Key, KeyInit}; let key = Key::::from([0u8; 64]); let cipher = Aes256SivAead::new(&key); ``` -------------------------------- ### Example: Initialize Aes256Ccm Cipher Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/ccm.md Demonstrates how to create a specific CCM cipher instance (Aes256Ccm) with a 32-byte key, a 10-byte tag, and a 13-byte nonce. ```rust use aes::Aes256; use ccm::{Ccm, Key, KeyInit, consts::{U10, U13}}; pub type Aes256Ccm = Ccm; let key = Key::::from([0u8; 32]); let cipher = Aes256Ccm::new(&key); ``` -------------------------------- ### OCB3 AEAD Usage Example Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Demonstrates how to initialize and use the Aes256Ocb3 cipher for encryption and decryption. Requires the `alloc`, `getrandom`, and `zeroize` features. ```rust use ocb3::{Aes256Ocb3, Key, KeyInit, Nonce, aead::{Aead, Generate}}; let key = Key::::generate(); let cipher = Aes256Ocb3::new(&key); let nonce = Nonce::generate(); let ct = cipher.encrypt(&nonce, b"msg")?; let pt = cipher.decrypt(&nonce, ct.as_ref())?; ``` -------------------------------- ### XAES-256-GCM Usage Example Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Demonstrates how to generate a key, initialize the XAES-256-GCM cipher, generate a nonce, encrypt a message, and decrypt it. Requires the `alloc` and `getrandom` features. ```rust use xaes_256_gcm::{XAes256Gcm, Key, KeyInit, Nonce, aead::{Aead, Generate}}; let key = Key::::generate(); let cipher = XAes256Gcm::new(&key); let nonce = Nonce::generate(); let ct = cipher.encrypt(&nonce, b"msg")?; let pt = cipher.decrypt(&nonce, ct.as_ref())?; ``` -------------------------------- ### EAX Encryption and Decryption Example Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Demonstrates how to use Aes256Eax for encrypting and decrypting a message. Requires the 'alloc' and 'getrandom' features. ```rust use eax::{Aes256Eax, Key, KeyInit, Nonce, aead::{Aead, Generate}}; let key = Key::::generate(); let cipher = Aes256Eax::new(&key); let nonce = Nonce::generate(); let ct = cipher.encrypt(&nonce, b"msg")?; let pt = cipher.decrypt(&nonce, ct.as_ref())?; ``` -------------------------------- ### MGM Usage Example Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Demonstrates how to use the Aes256Mgm cipher for encryption and decryption. Ensure the 'alloc' and 'getrandom' features are enabled. ```rust use mgm::{Aes256Mgm, Key, KeyInit, Nonce, aead::{Aead, Generate}}; let key = Key::::generate(); let cipher = Aes256Mgm::new(&key); let nonce = Nonce::generate(); let ct = cipher.encrypt(&nonce, b"msg")?; let pt = cipher.decrypt(&nonce, ct.as_ref())?; ``` -------------------------------- ### Deoxys AEAD Usage Example Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Demonstrates how to initialize and use the DeoxysI256 cipher for encryption and decryption. Requires the `alloc`, `getrandom`, and `zeroize` features. ```rust use deoxys::{DeoxysI256, Key, KeyInit, Nonce, aead::Aead}; let key = Key::::from([0u8; 32]); let cipher = DeoxysI256::new(&key); let nonce = Nonce::from([0u8; 16]); let ct = cipher.encrypt(&nonce, b"msg")?; let pt = cipher.decrypt(&nonce, ct.as_ref())?; ``` -------------------------------- ### Ascon-AEAD128 Usage Example Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Demonstrates how to use the AsconAead128 cipher for encryption and decryption. Requires the 'alloc' and 'getrandom' features. ```rust use ascon_aead128::{ AsconAead128, AsconAead128Key, AsconAead128Nonce, aead::{Aead, Generate, KeyInit, AeadCore} }; let key = AsconAead128Key::generate(); let cipher = AsconAead128::new(&key); let nonce = AsconAead128Nonce::generate(); let ciphertext = cipher.encrypt(&nonce, b"plaintext")?; let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?; ``` -------------------------------- ### Embedded Systems Configuration Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Cargo.toml configuration for embedded systems. This setup enables stack-based in-place operations, sensitive data wiping, and no allocation. ```toml [dependencies] aes-gcm = { version = "0.11", default-features = false, features = ["aes", "arrayvec", "zeroize"] } ``` -------------------------------- ### Disable `zeroize` Feature in TOML Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Example TOML configuration to disable the `zeroize` feature while keeping other features like `aes`, `alloc`, and `getrandom` enabled. ```toml [dependencies] aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc", "getrandom"] } ``` -------------------------------- ### Hashing Associated Data for Encryption Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/errors.md Shows how to hash excessively large associated data before encryption to avoid exceeding A_MAX limits, using SHA-256 as an example. ```rust use sha2::{Digest, Sha256}; use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce}; let huge_aad = vec![0u8; (1u64 << 61) as usize]; // Hash AAD first let mut hasher = Sha256::new(); hasher.update(&huge_aad); let aad_hash = hasher.finalize(); let key = Key::::from([0u8; 32]); let cipher = Aes256Gcm::new(&key); let nonce = Nonce::from([0u8; 12]); // Use hash as AAD instead cipher.encrypt(&nonce, &aad_hash, b"plaintext")?; ``` -------------------------------- ### Handling Generic Encryption Failures Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/errors.md A basic example of handling potential `Err(Error)` during encryption, including rare cases like memory allocation failures or implementation bugs. It suggests logging and error propagation. ```rust use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce}; let key = Key::::from([0u8; 32]); let cipher = Aes256Gcm::new(&key); let nonce = Nonce::from([0u8; 12]); match cipher.encrypt(&nonce, b"msg") { Ok(ct) => println!("Encrypted: {:?}", ct), Err(Error) => { eprintln!("Encryption failed"); return Err(Box::new(Error)); } } ``` -------------------------------- ### XAES-256-GCM Constructor Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Implementation of the `KeyInit` trait for XAES-256-GCM, providing a method to initialize the cipher with a given key. ```rust impl KeyInit for XAes256Gcm { fn new(key: &Key) -> Self> } ``` -------------------------------- ### OCB3 Constructor Implementation Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Implementation of the KeyInit trait for Ocb3, providing the `new` function to construct an Ocb3 cipher instance from a secret key. ```rust impl KeyInit for Ocb3 where C: BlockSizeUser + BlockCipherEncrypt + KeyInit, N: ArraySize, T: ArraySize, { fn new(key: &Key) -> Self } ``` -------------------------------- ### XAES-256-GCM Constructor and Usage Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Demonstrates how to initialize XAES-256-GCM with a generated key and perform encryption and decryption operations. ```APIDOC ## XAES-256-GCM ### Constructor ```rust impl KeyInit for XAes256Gcm { fn new(key: &Key) -> Self } ``` ### Usage ```rust use xaes_256_gcm::{XAes256Gcm, Key, KeyInit, Nonce, aead::{Aead, Generate}}; let key = Key::::generate(); let cipher = XAes256Gcm::new(&key); let nonce = Nonce::generate(); let ct = cipher.encrypt(&nonce, b"msg")?; let pt = cipher.decrypt(&nonce, ct.as_ref())?; ``` ### Algorithm Details - **Key Size:** 512 bits (64 bytes) - double standard AES-256 - **Nonce Size:** 96 bits (12 bytes) - **Tag Size:** 128 bits (16 bytes) - **Purpose:** Extended key AES for additional security margin - **Encryption:** AES-256 in counter mode with GHASH authentication ``` -------------------------------- ### Manual Key Generation Without `getrandom` Feature Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Shows how to manually create a key from pre-generated bytes when the `getrandom` feature is not enabled. Ensure `key_bytes` is populated with actual entropy. ```rust use aes_gcm::{Key, Nonce, KeyInit}; // Works without getrandom - use pre-generated bytes let key_bytes = [0u8; 32]; // Replace with actual entropy let key = Key::::from(key_bytes); ``` -------------------------------- ### Custom AES Implementation Pattern Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Demonstrates how to use a custom AES implementation with `AesGcm` by defining a `CustomAes` struct that implements necessary traits like `KeyInit` and `BlockCipherEncrypt`. ```rust use aes_gcm::AesGcm; use cipher::{BlockCipherEncrypt, BlockSizeUser, KeyInit}; // Use custom AES implementation struct CustomAes; impl KeyInit for CustomAes { /* ... */ } impl BlockCipherEncrypt for CustomAes { /* ... */ } impl BlockSizeUser for CustomAes { type BlockSize = U16; } // Create cipher with custom AES type CustomGcm = AesGcm; ``` -------------------------------- ### Encrypt and Decrypt with AES-256-GCM-SIV Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm-siv.md Demonstrates the basic encryption and decryption flow using AES-256-GCM-SIV. Ensure you have the necessary key and nonce. The nonce can be generated normally as reuse is handled gracefully. ```rust use aes_gcm_siv::{Aes256GcmSiv, Key, KeyInit, Nonce, aead::{Aead, AeadCore, Generate}}; // Generate key let key = Key::::generate(); let cipher = Aes256GcmSiv::new(&key); // Note: Nonce can be generated normally; reuse is handled gracefully let nonce = Nonce::from([0u8; 12]); // Encrypt let ciphertext = cipher.encrypt(&nonce, b"plaintext")?; // Decrypt let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?; assert_eq!(plaintext, b"plaintext"); ``` -------------------------------- ### Generate Random Key and Nonce with `getrandom` Feature Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Demonstrates generating a random key and nonce using the `getrandom` feature. This requires the `getrandom` feature to be enabled. ```rust use aes_gcm::{Key, Nonce, KeyInit, aead::AeadCore}; // Requires getrandom feature let key = Key::::generate(); let nonce = Nonce::generate(); ``` -------------------------------- ### OCB3 AEAD Cipher Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Documentation for the OCB3 AEAD cipher, a high-performance authenticated encryption mode. It covers main types, struct definition, constructor, algorithm details, and a usage example. ```APIDOC ## OCB3 AEAD Cipher ### Description Offset Codebook (OCB) mode 3 is a high-performance AEAD cipher. ### Main Types - `Aes128Ocb3`: OCB3 with AES-128. - `Aes256Ocb3`: OCB3 with AES-256. - `Nonce`: 15-byte nonce. - `Tag`: 16-byte tag. ### Constructor - `Ocb3::new(key: &Key) -> Self`: Initializes the OCB3 cipher with a given key. ### Algorithm Details - **Nonce Size:** 15 bytes (120 bits, default) - **Tag Size:** 16 bytes (128 bits, default) - **Encryption:** Parallelizable block cipher mode - **Authentication:** OCB checksum ### Usage Example ```rust use ocb3::{Aes256Ocb3, Key, KeyInit, Nonce, aead::{Aead, Generate}}; let key = Key::::generate(); let cipher = Aes256Ocb3::new(&key); let nonce = Nonce::generate(); let ct = cipher.encrypt(&nonce, b"msg")?; let pt = cipher.decrypt(&nonce, ct.as_ref())?; ``` ``` -------------------------------- ### Deoxys AEAD Cipher Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Documentation for the Deoxys AEAD cipher, including its iterative (Deoxys-I-256) and parallel (Deoxys-II-256) variants. It details the main types, struct definition, constructor, and provides a usage example. ```APIDOC ## Deoxys AEAD Cipher ### Description Deoxys AEAD cipher (Deoxys-I-256, Deoxys-II-256) provides authenticated encryption. ### Main Types - `DeoxysI256`: Iterative version. - `DeoxysII256`: Parallel version. - `Nonce`: 16-byte nonce. - `Tag`: 16-byte tag. ### Constructor - `Deoxys::new(key: &Key) -> Self`: Initializes the Deoxys cipher with a given key. ### Usage Example ```rust use deoxys::{DeoxysI256, Key, KeyInit, Nonce, aead::Aead}; let key = Key::::from([0u8; 32]); let cipher = DeoxysI256::new(&key); let nonce = Nonce::from([0u8; 16]); let ct = cipher.encrypt(&nonce, b"msg")?; let pt = cipher.decrypt(&nonce, ct.as_ref())?; ``` ``` -------------------------------- ### In-Place AEAD Encryption with ArrayVec Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/ccm.md Perform encryption without allocations using `arrayvec` for in-place operations. This example shows encrypting data directly within a mutable `ArrayVec` buffer, appending the authentication tag to the end. ```rust use aes::Aes256; use ccm::{ Ccm, Key, KeyInit, Nonce, aead::{AeadInOut, AeadCore, arrayvec::ArrayVec}, consts::{U10, U13} }; pub type Aes256Ccm = Ccm; let key = Key::::from([0u8; 32]); let cipher = Aes256Ccm::new(&key); let nonce = Nonce::::from([0u8; 13]); let mut buffer: ArrayVec = ArrayVec::new(); buffer.try_extend_from_slice(b"plaintext").unwrap(); cipher.encrypt_in_place(&nonce, b"", &mut buffer)?; // buffer now contains ciphertext with appended 10-byte tag ``` -------------------------------- ### Deoxys Constructor Implementation Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Implementation of the KeyInit trait for Deoxys, providing the `new` function to construct a Deoxys cipher instance from a secret key. ```rust impl KeyInit for Deoxys where C: BlockSizeUser + BlockCipherEncrypt + KeyInit, N: ArraySize, T: ArraySize, { fn new(key: &Key) -> Self } ``` -------------------------------- ### Ascon Constructor Implementation Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Implements the KeyInit trait for the Ascon struct, providing a constructor to initialize the cipher with a key. ```rust impl KeyInit for Ascon

{ fn new(key: &Key) -> Self } ``` -------------------------------- ### Belt-DWP Constructor Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Implements the KeyInit trait for BeltDwpCipher, providing a constructor to initialize the cipher with a key. ```rust impl KeyInit for BeltDwpCipher { fn new(key: &Key) -> Self } ``` -------------------------------- ### SivAead Constructor Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Initializes a new SIV AEAD cipher instance using the provided cryptographic key. The key size depends on the underlying block cipher and MAC algorithm used. ```APIDOC ## `SivAead::new` ### Description Creates a new SIV-AEAD cipher from a cryptographic key. The key is used for both encryption and authentication. ### Method `new` ### Parameters #### Request Body - **key** (`&Key`) - Required - Combined encryption and authentication key (256 or 512 bits depending on the cipher variant). ### Request Example ```rust use aes_siv::{Aes256SivAead, Key, KeyInit}; let key = Key::::from([0u8; 64]); let cipher = Aes256SivAead::new(&key); ``` ### Response #### Success Response (200) - **cipher instance** (`SivAead`) - The initialized SIV AEAD cipher instance. #### Response Example ```rust // Cipher instance is returned by the new function ``` ``` -------------------------------- ### In-Place Operations for Embedded Systems (No Allocation) Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/errors.md Demonstrates encryption using in-place operations with `ArrayVec` for embedded systems where memory allocation failures are not possible. Requires the `no_std` environment. ```rust use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce, aead::arrayvec::ArrayVec}; #[no_std] fn encrypt_no_std() -> Result<(), Error> { let mut buffer: ArrayVec = ArrayVec::new(); buffer.try_extend_from_slice(b"msg").unwrap(); cipher.encrypt_in_place(&nonce, b"", &mut buffer)?; Ok(()) } ``` -------------------------------- ### ChaChaPoly1305 Constructor Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/chacha20poly1305.md Initializes a new ChaCha20-Poly1305 cipher instance with a given 256-bit key. ```APIDOC ## ChaChaPoly1305::new ### Description Creates a new ChaCha20-Poly1305 cipher from a key. ### Method Associated function (constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **key** (`&Key`) - Required - 256-bit (32-byte) shared secret key ### Request Example ```rust use chacha20poly1305::{ChaCha20Poly1305, Key, KeyInit}; let key = Key::from([0u8; 32]); let cipher = ChaCha20Poly1305::new(&key); ``` ### Response #### Success Response - **Self** (`ChaChaPoly1305`) - An initialized cipher instance. #### Response Example None explicitly provided in source, but the type is `ChaChaPoly1305`. ``` -------------------------------- ### Run Memory Profiling with Valgrind Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Builds the Rust application and then runs it under Valgrind for memory profiling on Linux. Ensure the application is built in debug mode for effective profiling. ```bash # With valgrind (Linux) cargo build valgrind ./target/debug/app ``` -------------------------------- ### Rust: Constant-Time Tag Comparison Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/errors.md Illustrates the principle of constant-time comparison for authentication tags using the `subtle` crate. This ensures resistance against timing attacks, regardless of whether the tags match or not. ```rust // All AEAD implementations use constant-time comparisons // From subtle crate: use subtle::ConstantTimeEq; let computed_tag = compute_tag(..); let received_tag = get_tag_from_message(..); // Comparison takes same time regardless of mismatch position if computed_tag.ct_eq(&received_tag).into() { // Tag matches - proceed with decryption } else { // Tag mismatch - return error return Err(Error); } ``` -------------------------------- ### Initialize ChaCha20-Poly1305 Cipher Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/chacha20poly1305.md Creates a new ChaCha20-Poly1305 cipher instance using a provided 256-bit key. This function is part of the `KeyInit` trait implementation for `ChaChaPoly1305`. ```rust impl KeyInit for ChaChaPoly1305 where N: ArraySize, { fn new(key: &Key) -> Self } ``` ```rust use chacha20poly1305::{ChaCha20Poly1305, Key, KeyInit}; let key = Key::from([0u8; 32]); let cipher = ChaCha20Poly1305::new(&key); ``` -------------------------------- ### Set Minimum Supported Rust Version (MSRV) Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Verify the minimum supported Rust version (MSRV) for the project by setting the rustup override and building the project. This ensures compatibility with the specified Rust toolchain. ```bash rustup override set 1.85 cargo build ``` -------------------------------- ### EAX Constructor Implementation Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Implements the KeyInit trait for the EAX struct, providing a constructor to initialize the cipher with a key. ```rust impl KeyInit for Eax where C: BlockSizeUser + BlockCipherEncrypt + KeyInit, N: ArraySize, T: ArraySize, { fn new(key: &Key) -> Self } ``` -------------------------------- ### Force Getrandom Backend Selection Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Manually configure the getrandom backend by setting the GETRANDOM_IGNORE_INSECURE environment variable. This overrides the default platform-specific entropy source selection. ```bash GETRANDOM_IGNORE_INSECURE=1 cargo run ``` -------------------------------- ### In-Place Encryption with Aes256SivAead Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Shows how to perform encryption in-place using `encrypt_in_place` for scenarios requiring no allocations. The buffer will contain the SIV tag followed by the ciphertext. ```rust use aes_siv::{Aes256SivAead, Key, KeyInit, Nonce, aead::{AeadInOut, AeadCore, arrayvec::ArrayVec}}; let key = Key::::from([0u8; 64]); let cipher = Aes256SivAead::new(&key); let nonce = Nonce::from([0u8; 16]); let mut buffer: ArrayVec = ArrayVec::new(); buffer.try_extend_from_slice(b"plaintext").unwrap(); cipher.encrypt_in_place(&nonce, b"", &mut buffer)?; // buffer now contains SIV tag (16 bytes) followed by ciphertext ``` -------------------------------- ### AeadCore Implementation Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm-siv.md Provides core AEAD properties like nonce size, tag size, and tag position for AesGcmSiv. ```APIDOC ## AeadCore Implementation ### Description Core AEAD trait exposing nonce and tag sizes. ### Associated Types - `NonceSize`: 96-bit (12 bytes) - `TagSize`: 128-bit (16 bytes) - `TAG_POSITION`: Postfix (tag appended to ciphertext) ``` -------------------------------- ### KeySizeUser Implementation for SivAead Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Exposes the combined key size for encryption and authentication keys used by SivAead. ```rust impl KeySizeUser for SivAead where C: KeySizeUser, M: KeySizeUser, NonceSize: ArraySize + IsGreaterOrEqual, { type KeySize = >::Output; } ``` -------------------------------- ### Build for No-std Targets with Specific Features Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Compile a Rust project for no-std targets, such as ARM Cortex-M microcontrollers, by disabling default features and enabling specific ones like 'aes'. Adjustments for buffers and entropy sources may be required. ```bash cargo build --no-default-features --features "aes" --target thumbv7em-none-eabihf ``` -------------------------------- ### Encrypt Method (alloc feature) Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aead-stream.md Encrypts plaintext and associated data, returning the ciphertext and authentication tag as a new vector. Requires the 'alloc' feature. ```rust @cfg(feature = "alloc") fn encrypt<'msg, 'aad>( &self, position: Self::Counter, last_block: bool, plaintext: impl Into>, ) -> Result>; ``` -------------------------------- ### In-Place Encryption with AES-GCM-SIV (ArrayVec) Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm-siv.md Shows how to perform in-place encryption using AES-GCM-SIV with the `arrayvec` feature for scenarios requiring no allocations. The ciphertext and tag are appended to the existing buffer. ```rust use aes_gcm_siv::{Aes256GcmSiv, Key, KeyInit, Nonce, aead::{AeadInOut, AeadCore, arrayvec::ArrayVec}}; let key = Key::::from([0u8; 32]); let cipher = Aes256GcmSiv::new(&key); let nonce = Nonce::from([0u8; 12]); let mut buffer: ArrayVec = ArrayVec::new(); buffer.extend_from_slice(b"plaintext"); cipher.encrypt_in_place(&nonce, b"", &mut buffer)?; // buffer now contains ciphertext with appended tag ``` -------------------------------- ### Create AesGcmSiv Cipher with Key Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm-siv.md Constructs a new AES-GCM-SIV cipher instance using a provided cryptographic key. The key size should be 128 or 256 bits. ```rust impl KeyInit for AesGcmSiv where Aes: BlockSizeUser + BlockCipherEncrypt + KeyInit, NonceSize: ArraySize, { fn new(key: &Key) -> Self } ``` ```rust use aes_gcm_siv::{Aes256GcmSiv, Key, KeyInit}; let key = Key::::from([0u8; 32]); let cipher = Aes256GcmSiv::new(&key); ``` -------------------------------- ### MGM Constructor Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/additional-aeads.md Implements the KeyInit trait for the Mgm struct, providing a constructor to initialize the cipher with a key. ```rust impl KeyInit for Mgm where C: BlockSizeUser + BlockCipherEncrypt + KeyInit, N: ArraySize, T: ArraySize, { fn new(key: &Key) -> Self } ``` -------------------------------- ### Encrypting Multiple Messages with AEAD Stream Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aead-stream.md Demonstrates how to encrypt a sequence of messages using an AEAD stream primitive. Ensure the correct STREAM variant and nonce size are used for the chosen algorithm. ```rust use aead_stream::{NewStream, StreamPrimitive}; use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce, aead::{KeyInit, Generate}}; // For ChaCha20Poly1305 with STREAM type Stream = /* STREAM variant */; let key = Key::generate(); let nonce = /* 8-byte nonce, since ChaCha20 is 12 bytes - 4 byte overhead */; // Create stream primitive let stream = Stream::new(&key, &nonce); let mut encryptor = stream.encryptor(); // Encrypt multiple messages encryptor.next(b"aad1", &mut buf1)?; encryptor.next(b"aad2", &mut buf2)?; encryptor.last(b"aad3", &mut buf3)?; ``` -------------------------------- ### Advanced SIV Module Usage Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Introduces the `siv` submodule for advanced users needing fine-grained control over the SIV algorithm, including direct use for key derivation. ```rust use aes_siv::siv::{Siv, SivCore}; use aes::Aes256; use cmac::Cmac; // Use Siv directly for more control over key derivation ``` -------------------------------- ### KeyInit Trait Definition Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/types.md Trait for initializing a cipher from a cryptographic key. All AEAD implementations implement this trait. ```rust pub trait KeyInit: KeySizeUser { fn new(key: &Key) -> Self; } ``` -------------------------------- ### Encrypt and Decrypt with Aes128Ocb3 Source: https://github.com/rustcrypto/aeads/blob/master/ocb3/README.md Demonstrates basic encryption and decryption using Aes128Ocb3. Ensure the nonce is unique per message. This snippet requires the `aes`, `ocb3`, and `aead` crates. ```rust use aes::Aes128; use ocb3::{ aead::{Aead, AeadCore, Generate, Key, KeyInit, array::Array}, consts::U12, Ocb3, Nonce }; type Aes128Ocb3 = Ocb3; let key = Key::::generate(); let cipher = Aes128Ocb3::new(&key); let nonce = Nonce::generate(); // MUST be unique per message let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref()).unwrap(); let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref()).unwrap(); assert_eq!(&plaintext, b"plaintext message"); ``` -------------------------------- ### Run Memory Profiling with heaptrack Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Executes the Rust application using heaptrack for memory profiling on Linux. This tool helps identify memory leaks and usage patterns. ```bash # With heaptrack (Linux) heaptrack ./target/debug/app ``` -------------------------------- ### Automatic Key Zeroization with `zeroize` Feature Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Illustrates how sensitive data like keys is automatically zeroized when dropped, providing security against memory disclosure. This relies on the `zeroize` feature. ```rust use aes_gcm::{Aes256Gcm, Key, KeyInit}; { let key = Key::::from([0u8; 32]); let cipher = Aes256Gcm::new(&key); // cipher.key is zeroized on drop } // Memory automatically cleared ``` -------------------------------- ### Encrypt and Decrypt with AES-GCM Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm.md This snippet demonstrates high-level usage of AES-GCM for encryption and decryption. It shows how to generate a random key and nonce, encrypt plaintext with associated data, and then decrypt the ciphertext. Ensure the `aead` crate is included in your dependencies. ```rust use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce, aead::{Aead, AeadCore, Generate}}; // Generate random key and nonce let key = Key::::generate(); let cipher = Aes256Gcm::new(&key); let nonce = Nonce::generate(); // Encrypt with associated data let ciphertext = cipher.encrypt(&nonce, b"associated data", b"plaintext")?; // Decrypt let plaintext = cipher.decrypt(&nonce, &ciphertext[..], b"associated data")?; assert_eq!(plaintext, b"plaintext"); ``` -------------------------------- ### AesGcmSiv::new Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm-siv.md Constructs a new AES-GCM-SIV cipher instance using a cryptographic key. ```APIDOC ## Constructor: AesGcmSiv::new ### Description Creates a new AES-GCM-SIV cipher instance initialized with the provided cryptographic key. This is the primary way to instantiate the cipher for use. ### Method `new(key: &Key) -> Self` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **key** (`&Key`) - Required - The cryptographic key (128 or 256 bits) used to initialize the cipher. ### Request Example ```rust use aes_gcm_siv::{Aes256GcmSiv, Key, KeyInit}; let key = Key::::from([0u8; 32]); let cipher = Aes256GcmSiv::new(&key); ``` ### Response #### Success Response (200) - **Self** (`AesGcmSiv`) - An initialized AES-GCM-SIV cipher instance. #### Response Example (Instance of `AesGcmSiv`) ``` -------------------------------- ### Configure Workspace Dependencies in Cargo.toml Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Define workspace members and shared dependencies in Cargo.toml for projects using multiple AEAD crates. This allows for version and feature management across crates. ```toml [workspace] members = ["app", "crypto"] resolver = "2" [workspace.dependencies] aes-gcm = { version = "0.11", features = ["aes", "alloc", "getrandom"] } chacha20poly1305 = { version = "0.10", features = ["alloc", "getrandom"] } aead = "0.6" [dependencies] aes-gcm.workspace = true chacha20poly1305.workspace = true ``` -------------------------------- ### Initialize CCM Cipher with Key Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/ccm.md Creates a new CCM cipher instance using a cryptographic key. This constructor is suitable when you have the key readily available and want to initialize the cipher with specific AES variants and tag/nonce sizes. ```rust impl KeyInit for Ccm where C: BlockSizeUser + BlockCipherEncrypt + KeyInit, M: ArraySize + TagSize, N: ArraySize + NonceSize, { fn new(key: &Key) -> Self } ``` -------------------------------- ### Testing/CI Configuration Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Cargo.toml configuration for testing and CI environments. Note that dev dependencies can use full features, while production dependencies use a minimal set. ```toml [dev-dependencies] aes-gcm = { version = "0.11", features = ["aes", "alloc", "getrandom"] } [dependencies] aes-gcm = { version = "0.11", default-features = false, features = ["aes"] } ``` -------------------------------- ### Encrypt and Decrypt with Aes256SivAead Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Demonstrates basic encryption and decryption using the `Aead` trait with `Aes256SivAead`. Supports deterministic encryption and nonce reuse. ```rust use aes_siv::{Aes256SivAead, Key, KeyInit, Nonce, aead::{Aead, AeadCore, Generate}}; let key = Key::::generate(); let cipher = Aes256SivAead::new(&key); // Note: Can reuse nonce (deterministic encryption) let nonce = Nonce::from([0u8; 16]); // Encrypt - deterministic output let ciphertext = cipher.encrypt(&nonce, b"plaintext")?; // Decrypt let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?; assert_eq!(plaintext, b"plaintext"); // Re-encrypting same input produces same ciphertext let ciphertext2 = cipher.encrypt(&nonce, b"plaintext")?; assert_eq!(ciphertext, ciphertext2); ``` -------------------------------- ### Standard Application Configuration Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Default Cargo.toml configuration for a standard application. This enables all default features, including allocation and random generation. ```toml aes-gcm = "0.11" # All default features ``` -------------------------------- ### AesGcm Constructor: new Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm.md Creates a new AES-GCM cipher from a cryptographic key. The key size (128 or 256 bits) depends on the Aes type. Use this for standard key initialization. ```rust impl KeyInit for AesGcm where Aes: BlockSizeUser + BlockCipherEncrypt + KeyInit, TagSize: TagSize, { fn new(key: &Key) -> Self } ``` ```rust use aes_gcm::{Aes256Gcm, Key, KeyInit}; let key = Key::::from([0u8; 32]); let cipher = Aes256Gcm::new(&key); ``` -------------------------------- ### Enable Allocating Operations with `alloc` Feature Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Configure TOML to disable default features and explicitly enable the `aes` feature for AES-GCM, allowing for heap-allocated encryption/decryption operations. ```toml [dependencies] aes-gcm = { version = "0.11", default-features = false, features = ["aes"] } ``` -------------------------------- ### Rust: Encrypt In-Place with Insufficient Buffer Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/errors.md Demonstrates an in-place encryption failure when the provided buffer is too small to hold the resulting ciphertext and authentication tag. The buffer remains unchanged upon error. ```rust use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce, aead::arrayvec::ArrayVec}; let key = Key::::from([0u8; 32]); let cipher = Aes256Gcm::new(&key); let nonce = Nonce::from([0u8; 12]); let mut buffer: ArrayVec = ArrayVec::new(); buffer.try_extend_from_slice(b"plaintext").unwrap(); // Buffer is 9 bytes; ciphertext + 16-byte tag = 25 bytes needed // This will fail let result = cipher.encrypt_in_place(&nonce, b"", &mut buffer); assert!(result.is_err()) ``` -------------------------------- ### AeadInOut Implementation for SivAead Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Low-level in-place encryption and decryption with detached authentication tags for SivAead. ```rust impl AeadInOut for SivAead where C: BlockSizeUser + BlockCipherEncrypt, M: Mac + FixedOutputReset + KeyInit + Clone, NonceSize: ArraySize + IsGreaterOrEqual, { fn encrypt_inout_detached( &self, nonce: &Nonce, associated_data: &[u8], buffer: InOutBuf<'_, '_, u8>, ) -> Result fn decrypt_inout_detached( &self, nonce: &Nonce, associated_data: &[u8], buffer: InOutBuf<'_, '_, u8>, tag: &Tag, ) -> Result<(), Error> } ``` -------------------------------- ### Configure Cargo Development, Release, and Bench Profiles Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Defines Cargo build profiles for development (debug symbols, no optimizations), release (optimizations enabled), and benchmarking (optimizations, single codegen unit). ```toml [profile.dev] opt-level = 0 debug = true [profile.release] opt-level = 3 lto = true [profile.bench] opt-level = 3 lto = true codegen-units = 1 ``` -------------------------------- ### Enable `hazmat` Feature for Short Authentication Tags Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Configure TOML to enable the `hazmat` feature for `aes-gcm`, allowing the use of short authentication tags like 32-bit and 64-bit. Use with caution due to weak authentication. ```toml [dependencies] aes-gcm = { version = "0.11", features = ["aes", "hazmat"] } ``` -------------------------------- ### Create AesGcmSiv Cipher from Existing Instance Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm-siv.md Creates an AES-GCM-SIV cipher from an already initialized AES block cipher instance. This allows reusing existing cipher objects. ```rust impl From for AesGcmSiv where Aes: BlockSizeUser + BlockCipherEncrypt, NonceSize: ArraySize, { fn from(cipher: Aes) -> Self } ``` -------------------------------- ### Ccm::new Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/ccm.md Creates a new CCM cipher instance using a provided cryptographic key. This constructor is suitable when you have the raw key material and need to initialize the cipher. ```APIDOC ## Ccm::new ### Description Creates a new CCM cipher from a cryptographic key. ### Method `new(key: &Key) -> Self` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use aes::Aes256; use ccm::{Ccm, Key, KeyInit, consts::{U10, U13}}; pub type Aes256Ccm = Ccm; let key = Key::::from([0u8; 32]); let cipher = Aes256Ccm::new(&key); ``` ### Response #### Success Response (200) `Ccm` - initialized cipher instance #### Response Example None provided in source. ``` -------------------------------- ### Build for WASM Targets Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/configuration.md Compile a Rust project for WebAssembly (WASM) targets, disabling default features and enabling specific ones like 'aes'. Note that the 'getrandom' feature requires a JavaScript environment for WASM builds. ```bash cargo build --target wasm32-unknown-unknown --no-default-features --features "aes" ``` -------------------------------- ### Rust: Decrypt with Short Ciphertext Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/errors.md Shows how decryption fails when the provided ciphertext is shorter than the expected authentication tag size. This indicates a truncated or improperly formatted message. ```rust use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce}; let key = Key::::from([0u8; 32]); let cipher = Aes256Gcm::new(&key); let nonce = Nonce::from([0u8; 12]); // Too short (less than 16-byte tag) let short_ciphertext = b"short"; let result = cipher.decrypt(&nonce, short_ciphertext); assert!(result.is_err()) ``` -------------------------------- ### AesGcmSiv AeadInOut Implementation Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm-siv.md Provides low-level in-place encryption and decryption operations for AesGcmSiv. ```rust impl AeadInOut for AesGcmSiv where Aes: BlockSizeUser + BlockCipherEncrypt, NonceSize: ArraySize, ``` -------------------------------- ### Illustrative Retry Logic (Not Recommended for AEAD) Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/errors.md Demonstrates a retry loop for handling potential transient errors. Note that AEAD decryption errors are typically deterministic and not suitable for retries. ```rust use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce}; fn decrypt_with_retry(cipher: &Aes256Gcm, nonce: &[u8; 12], ct: &[u8]) -> Result, String> { // AEAD errors are typically not retryable // This example is for illustration only for attempt in 1..=3 { match cipher.decrypt(nonce, ct) { Ok(pt) => return Ok(pt), Err(_) if attempt < 3 => { // Not recommended for AEAD - error is deterministic continue; } Err(_) => return Err("Authentication failed".to_string()), } } unreachable!() } ``` -------------------------------- ### Stream Encryption for Large Data Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/errors.md Illustrates using `aead_stream` for processing large data by chunking, as a recovery strategy for oversized messages. ```rust use aead_stream::{StreamPrimitive, NewStream}; // Use STREAM for large data let stream = StreamPrimitive::new(&key, &stream_nonce); let mut encryptor = stream.encryptor(); // Process chunks for chunk in large_data.chunks(1_000_000) { encryptor.next(b"", &mut buffer)?; } encryptor.last(b"", &mut buffer)?; ``` -------------------------------- ### AesGcm Constructor: from Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-gcm.md Creates an AES-GCM cipher from an existing AES block cipher instance. Useful when integrating with hardware-accelerated or custom AES implementations. ```rust impl From for AesGcm where Aes: BlockSizeUser + BlockCipherEncrypt, TagSize: TagSize, { fn from(cipher: Aes) -> Self } ``` ```rust use aes::{Aes256, cipher::KeyInit}; use aes_gcm::AesGcm; use cipher::consts::U12; let aes = Aes256::new(&[0u8; 32].into()); let gcm: AesGcm = aes.into(); ``` -------------------------------- ### Create Stateful Encryptor Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aead-stream.md Constructs a stateful encryptor object from a StreamPrimitive instance. This is useful for encrypting multiple messages sequentially. ```rust fn encryptor(self) -> Encryptor where Self: Sized, ``` -------------------------------- ### SivAead Core Properties Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Provides core AEAD trait information, including nonce size, tag size, and tag position. ```APIDOC ## AeadCore Core AEAD trait providing nonce and tag size information. **Associated Types:** - `NonceSize`: NonceSize (default 128 bits) - `TagSize`: U16 (128 bits) - `TAG_POSITION`: Prefix (tag prepended, unlike most AEADs which append) ``` -------------------------------- ### SivAead Key Size Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Exposes the combined key size for encryption and authentication keys. ```APIDOC ## KeySizeUser Exposes combined key size (encryption key + authentication key). ``` -------------------------------- ### AeadCore Implementation for SivAead Source: https://github.com/rustcrypto/aeads/blob/master/_autodocs/aes-siv.md Provides core AEAD trait information, including nonce size, tag size, and tag position for SivAead. ```rust impl AeadCore for SivAead where C: BlockSizeUser, NonceSize: ArraySize + IsGreaterOrEqual, { type NonceSize = NonceSize; type TagSize = U16; const TAG_POSITION: TagPosition = TagPosition::Prefix; } ```