AI & Data
Authenticated encryption with AES-256-GCM
A minimal encrypt and decrypt round trip with a fresh nonce per message.
Overview
A small Rust program using the audited aes-gcm crate: generate a 256-bit key, encrypt with a random 96-bit nonce, decrypt and assert the round trip. Practice for the note encryption used in the shielded pools.
The code
src/main.rsView on GitHub ↗
fn encrypt(plaintext: &str, key: &Key<Aes256Gcm>) -> (Vec<u8>, Vec<u8>) {
let cipher = Aes256Gcm::new(key);
let nonce = Aes256Gcm::generate_nonce(OsRng);
let ciphertext = cipher.encrypt(&nonce, plaintext.as_bytes()).expect("encryption failure");
(ciphertext, nonce.to_vec())
}
fn decrypt(ciphertext: &[u8], nonce_bytes: &[u8], key: &Key<Aes256Gcm>) -> String {
let cipher = Aes256Gcm::new(key);
let nonce = Nonce::from_slice(nonce_bytes);
let plaintext_bytes = cipher.decrypt(nonce, ciphertext).expect("decryption failure");
String::from_utf8(plaintext_bytes).expect("invalid UTF-8")
}
How it works
- Random key and nonce from the OS RNG
- Ciphertext includes the GCM tag, so tampering fails decryption