Answer#
Encryption alone hides content but does not prove that nobody changed it. Authenticated encryption with associated data (AEAD) does both: decryption fails if even one bit of the ciphertext was altered. For most application code, use an AEAD from a maintained library and do not assemble your own constructions from primitives.
Two rules decide whether it is secure:
- The key is random, secret and stored outside the source code (see the thread on secrets).
- The nonce is unique for each message under one key. With AES-GCM, repeating a nonce with the same key breaks the confidentiality and authenticity of the messages involved. Random 96-bit nonces are acceptable at moderate volumes; the crate documentation and NIST's guidance on GCM discuss limits for very large numbers of messages.
[dependencies]
aes-gcm = "0.10"use aes_gcm::{
aead::{Aead, AeadCore, KeyInit, OsRng},
Aes256Gcm, Key, Nonce,
};
fn encrypt(key: &Key<Aes256Gcm>, plaintext: &[u8]) -> Vec<u8> {
let cipher = Aes256Gcm::new(key);
let nonce = Aes256Gcm::generate_nonce(&mut OsRng); // 96 bits, new for every message
let mut out = nonce.to_vec();
out.extend(cipher.encrypt(&nonce, plaintext).expect("encryption failed"));
out // nonce first, then ciphertext and authentication tag
}
fn decrypt(key: &Key<Aes256Gcm>, data: &[u8]) -> Option<Vec<u8>> {
if data.len() < 12 {
return None;
}
let (nonce, ct) = data.split_at(12);
Aes256Gcm::new(key).decrypt(Nonce::from_slice(nonce), ct).ok()
}
fn main() {
let key = Aes256Gcm::generate_key(OsRng); // keep real keys out of source code
let sealed = encrypt(&key, b"card ending 4242");
println!("round trip: {:?}", decrypt(&key, &sealed).map(|v| String::from_utf8(v).unwrap()));
let mut tampered = sealed.clone();
let last = tampered.len() - 1;
tampered[last] ^= 1;
println!("tampered: {:?}", decrypt(&key, &tampered));
println!("same input twice differs: {}", encrypt(&key, b"x") != encrypt(&key, b"x"));
}round trip: Some("card ending 4242")
tampered: None
same input twice differs: trueThe output shows that the message round-trips, that a flipped bit makes decryption return None (the library reported an authentication failure), and that encrypting the same input twice gives different output because the nonce differs.
How to do it#
- Generate the key once with a secure generator, and store it in a secret manager or protected file.
- Prefix each message with its nonce, as above, and decrypt from that.
- Bind the ciphertext to its context with the associated data feature (for example the record ID), so that a ciphertext cannot be moved to another record.
- Plan key rotation: store a key identifier beside the ciphertext.
- Handle decryption failure as "data is invalid or tampered with", never as a reason to use the data anyway.
Common mistakes#
- Hard-coding the key, or deriving it from a short password directly. Use a password-based key derivation function when the key comes from a password.
- Using a fixed or counter nonce without a plan that guarantees it never repeats across restarts and servers.
- Using unauthenticated modes (such as plain CBC or CTR) for data an attacker could change.
- Encrypting passwords. Passwords are hashed, not encrypted (see the Argon2 thread).
Related questions#
Should I use a different algorithm, such as ChaCha20-Poly1305?#
It is also a sound AEAD, and the RustCrypto project provides it. The rules above (secret key, unique nonce) are the same.
How do I derive a key from a password?#
With a password-based key derivation function (Argon2 or PBKDF2) and a random salt, not a plain hash. The argon2 crate has hash_password_into for filling a key buffer; read its documentation for the version you use.
Sources#
aes-gcmdocumentation: https://docs.rs/aes-gcm/0.10.3/aes_gcm/- OWASP Cryptographic Storage Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html
- NIST SP 800-38D, "Recommendation for Block Cipher Modes of Operation: GCM": https://csrc.nist.gov/pubs/sp/800/38/d/final