Vitamin C AEAD
Authenticated Encryption with Associated Data (AEAD) primitives for building secure encryption systems.
This crate is part of the Vitamin C framework to make cryptography code healthy.
What is AEAD?
AEAD (Authenticated Encryption with Associated Data) is a form of encryption that provides both confidentiality and authenticity. It ensures that:
- Confidentiality: The plaintext is encrypted and cannot be read without the key
- Authenticity: The ciphertext cannot be modified without detection
- Associated Data: Additional data can be authenticated (but not encrypted) alongside the ciphertext
This crate provides traits and types for implementing AEAD operations in a safe and ergonomic way.
Key Features
- Composable encryption shape: The [
Cipher] trait is paired with [SeqCipher] and [MapCipher] sub-traits so a single cipher can drive byte, sequence, and map encryption with a consistent API - Visitor-pattern decryption: The [
Decrypt] / [Decipher] / [DecipherVisitor] trio mirrorsserde'sDeserialize/Deserializer/Visitor, letting types describe how they decrypt themselves independently of any specific cipher - Flexible AAD handling: The [
IntoAad] trait lets strings, byte slices, integers, tuples, and()all be used as additional authenticated data - Protected types integration: Works with
vitaminc-protectedso sensitive plaintext stays wrapped through encrypt and decrypt - Side-channel-aware errors: The [
Unspecified] error type reveals no information about the cause of a failure
Usage
Implementing the Cipher trait
A [Cipher] is consumed by the operation it drives — typically you implement it for a reference to your cipher state (&MyCipher) so the same cipher can be reused across many calls. The trait declares the output (Ok) and error types, plus associated types for sequence and map encryption:
use Any;
use ;
use Protected;
;
;
;
For a complete reference implementation see vitaminc_encrypt::Aes256Cipher.
Encrypting data
Once you have a Cipher implementation (typically for &MyCipher), use the [Encrypt] trait. Many built-in types already implement Encrypt:
use Encrypt;
// `cipher: MyCipher` where `Cipher` is implemented for `&MyCipher`.
// Encrypt a string
let encrypted_string = "secret message".encrypt?;
// Encrypt with additional authenticated data
let encrypted_with_aad = "secret".encrypt_with_aad?;
// Encrypt a byte array
let encrypted_bytes = .encrypt?;
// Encrypt a byte vector — a byte leaf, the same wire shape as the array
let encrypted_vec = vec!.encrypt?;
Note that Encrypt::encrypt consumes the cipher value. Implementing Cipher for &MyCipher (rather than MyCipher) means you can pass &cipher for each call and reuse the underlying state.
Decrypting data
Decryption uses a visitor pattern modelled on serde::Deserialize:
- A type that knows how to decrypt itself implements [
Decrypt]. - A cipher provides a [
Decipher] (typically wrapping a ciphertext + cipher state) that drives the decryption. - Concrete cipher implementations expose ergonomic decrypt entry points — for example,
Aes256Cipherprovidescipher.decrypt::<T>(ciphertext)andcipher.decrypt_with_aad::<T, _>(ciphertext, aad).
// Using a concrete cipher (see `vitaminc_encrypt::Aes256Cipher`):
let plaintext: String = cipher.decrypt?;
let plaintext: String = cipher.decrypt_with_aad?;
String, Vec<u8>, [u8; N], u32, Vec<T: Decrypt>, HashMap<String, T: Decrypt>, and Protected<T: Decrypt> all implement Decrypt out of the box.
Note on maps: both
HashMap<&'static str, T>andHashMap<String, T>implementEncrypt(keys are anythingInto<Cow<'static, str>>), and decryption yieldsHashMap<String, T>. Map keys travel in the clear but are bound into each value's AAD via [Aad::for_map_entry], so swapping or renaming keys inside a stored ciphertext causes decryption to fail.
Additional Authenticated Data (AAD)
Many types can be used as AAD through the [IntoAad] trait:
use Encrypt;
// String AAD
"my-secret".encrypt_with_aad?;
// Byte slice AAD
"my-secret".encrypt_with_aad?;
// Integer AAD
"my-secret".encrypt_with_aad?;
// Tuple AAD (PAE-encoded to prevent canonicalisation attacks)
"my-secret".encrypt_with_aad?;
// No AAD
"my-secret".encrypt_with_aad?;
Working with Protected Types
The crate integrates with vitaminc-protected so sensitive plaintext stays wrapped:
use Encrypt;
use Protected;
let sensitive_data = new;
let encrypted = sensitive_data.encrypt?;
The corresponding Decrypt impl for Protected<T> re-wraps the decrypted plaintext, so the value stays inside Protected end-to-end.
For the byte leaves — [u8; N], Vec<u8>, and String — "end-to-end" is literal. Protected<T>'s impls go through [Encrypt::encrypt_protected] and [Decrypt::decrypt_protected], and the byte leaves override those to hand the still-wrapped value straight to the cipher's Protected-taking entry points (Cipher::encrypt_bytes_array, Cipher::encrypt_bytes_vec, DecipherVisitor::visit_bytes_vec). String converts between its string and byte-buffer representations inside the wrapper (via Controlled::map), so a Protected<String> password, like a Protected<[u8; 32]> key, is never unwrapped on its way in or out. Composite types take the defaults, which unwrap to T and rely on each leaf re-wrapping its own payload before it reaches the cipher.
Because a derived newtype is transparent, #[derive(Encrypt)] struct Key(Protected<[u8; 32]>); gets exactly that path — no hand-written impl is needed to keep key material wrapped.
Deriving Encrypt and Decrypt
Most structs do not need a hand-written impl:
use ;
A derived struct is encrypted as a map keyed by field name, which is the shape that gets each field its own AAD binding: MapCipher seals every value against Aad::for_map_entry of its key, so a stored field cannot be renamed, or moved onto another key, without decryption failing. A sequence would give no such guarantee — element AAD carries no positional component, so two same-typed fields would be freely interchangeable.
What follows from that shape:
- Field names are part of the ciphertext contract. Renaming a field breaks compatibility with data already encrypted;
#[aead(rename = "...")]keeps the old wire key. - A derived struct's ciphertext is interchangeable with the equivalent
HashMap<String, _>ciphertext. - A tuple struct of two or more fields is keyed by decimal index (
"0","1", …), so its fields are bound the same way. - A newtype struct (exactly one unnamed field) is transparent — it encrypts and decrypts exactly as its inner type, adding nothing to the ciphertext. Wrapping an existing type is therefore not a wire-breaking change.
- A unit struct, or a struct with no fields, encrypts to the authenticated empty-map marker.
Decoding is strict. Entry order in a stored ciphertext is not authenticated, so the derived Decrypt reads keys first and matches them to fields; a missing field, an unknown key, or a duplicate key is rejected rather than defaulted or skipped, because an entry whose value is never decrypted is an entry whose AAD binding is never verified.
Enums are not supported: a ciphertext carries no authenticated variant discriminator, so any encoding the macro could pick would either leak the variant in the clear or leave it forgeable. Model the choice explicitly instead — for example as a struct of Option fields.
A field that should be stored in the clear — a plain database column other queries can read without the key — takes #[aead(passthrough)]. Such a field is neither encrypted nor authenticated; the derive's documentation spells out exactly what that gives up.
Use #[aead(crate = "...")] on the container when vitaminc_aead is reached through a re-export, e.g. #[aead(crate = "::vitaminc::aead")].
Custom Types
Where the derive's shape is not what you want, implement [Encrypt] and [Decrypt] by hand. The cases that call for it:
- Leaving fields out of the ciphertext entirely (as opposed to storing them in the clear, which is
#[aead(passthrough)]). - A non-map layout — a sequence, or a single leaf built from several fields.
- Transforming the AAD on the way through, as [
ContextTag] and [Element] do. - Enums, which the derive rejects.
For example, a User whose id and email live in ordinary columns and whose password_hash is encrypted is a derive with two passthrough fields:
use ;
But if id and email are not to be stored in this ciphertext at all, that is a hand-written impl:
use ;
The visitor pattern keeps the cipher and the type independent: the cipher decides how the ciphertext is laid out and how AAD is enforced, while the type decides how its fields are reassembled.
Passing fields through in the clear
Not every column of a table needs encrypting. A record usually has a few fields that other queries select, filter, or update without holding the key — a display name, a schema version, a plain id column — beside the ones that must be sealed. Wrap such a field in [Passthrough] and it is stored as a cleartext entry of the same ciphertext container, so the record still round-trips as one unit while that field stays an ordinary column.
Passthrough provides no security guarantees whatsoever. The value is not encrypted and not authenticated — it, and for map entries its key, can be read, edited, added, or removed in storage and every encrypted field beside it still decrypts. Treat what comes back as untrusted input: non-sensitive, non-security-deciding data only, never a field the program then trusts for authorization, tenancy, access control, or for choosing which encrypted record to trust. The full contract is documented once, under #[aead(passthrough)]; Passthrough<T> is the hand-written equivalent of that attribute.
Because a custom type's impl is generic over every cipher, it cannot name a particular cipher's passthrough payload type; Passthrough<T> drives the type-erased channel for it, through the same encrypt_entry / next_value calls as any encrypted field:
use ;
Anything secret-bearing belongs in Protected and gets encrypted; anything that must be tamper-evident but readable belongs in the AAD, not in a passthrough.
Nonce Generation
The crate provides nonce generation utilities for AEAD operations:
#
Security Considerations
- Always use unique nonces for each encryption operation with the same key
- Never reuse nonces with the same key, as this can compromise security
- The [
Unspecified] error type is used to prevent side-channel attacks by not revealing information about failures - When decrypting, always verify authentication before processing the plaintext
CipherStash
Vitamin C is brought to you by the team at CipherStash.
License: MIT