Cryptography in Rust
Cryptography sits underneath every part of computer security worth caring about. Passwords, encrypted comms, signatures, integrity checks, all of it. Rust's ecosystem ships solid crates for the job, fast enough not to make you hate using them.
The Golden Rule
Never roll your own crypto primitives. Reach for an audited library. Cryptography breaks in ways your tests will never see: the code passes, encrypts, decrypts, ships, and then a paper turns up showing it was wide open the whole time.
Choosing a Crate
| Crate | Focus | Status and review |
|---|---|---|
ring | Core primitives (AES, SHA, RSA) | Most of its C and assembly comes from BoringSSL; its README makes no audit claim |
RustCrypto (aes-gcm, chacha20poly1305, sha2, ...) | Broad coverage, pure Rust, one crate per algorithm | Maintained; review varies by crate. aes-gcm has had one audit, by NCC Group |
orion | High-level, easy-to-use | Maintained; its README says it "has not undergone any third-party security audit" |
sodiumoxide | libsodium bindings | Deprecated by its maintainer (RustSec advisory RUSTSEC-2021-0137) and no longer maintained. Avoid in new code |
"Audited" is a property of one version of one crate, so check the crate's own README or advisory history (and the RustSec database) for the version you depend on.
We'll lean on ring for primitives and argon2 for password hashing throughout the lesson.
Hashing
A cryptographic hash boils any input down to a fixed-size fingerprint:
use ring::digest;
fn hash_data(data: &[u8]) -> String { let hash = digest::digest(&digest::SHA256, data); hex_encode(hash.as_ref())}
fn hex_encode(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{:02x}", b)).collect()}
fn main() { let hash = hash_data(b"Hello, world!"); println!("SHA-256: {}", hash);
// Verify data integrity let original_hash = hash_data(b"important data"); let received_hash = hash_data(b"important data"); assert_eq!(original_hash, received_hash);}Never use a plain hash for passwords. SHA-256 is fast, which means attackers can try billions of guesses per second. Use a password-hashing function like Argon2 or bcrypt, which is deliberately slow.
Password Hashing with Argon2
Argon2 won the Password Hashing Competition and is the default recommendation for anything new:
use argon2::{ password_hash::{ rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString, }, Argon2,};
fn hash_password(password: &str) -> String { let salt = SaltString::generate(&mut OsRng); let argon2 = Argon2::default();
argon2 .hash_password(password.as_bytes(), &salt) .expect("Failed to hash password") .to_string()}
fn verify_password(password: &str, hash: &str) -> bool { let parsed_hash = PasswordHash::new(hash).expect("Invalid hash format"); Argon2::default() .verify_password(password.as_bytes(), &parsed_hash) .is_ok()}
fn main() { let hash = hash_password("my_secure_password"); println!("Hash: {}", hash);
assert!(verify_password("my_secure_password", &hash)); assert!(!verify_password("wrong_password", &hash));}Symmetric Encryption (AES-GCM)
AES-GCM does authenticated encryption. One pass, ciphertext plus an auth tag. Tampering blows up at decryption time:
use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey, AES_256_GCM};use ring::rand::{SecureRandom, SystemRandom};
fn encrypt(key_bytes: &[u8; 32], plaintext: &[u8]) -> Vec<u8> { let unbound_key = UnboundKey::new(&AES_256_GCM, key_bytes).unwrap(); let key = LessSafeKey::new(unbound_key);
let rng = SystemRandom::new(); let mut nonce_bytes = [0u8; 12]; rng.fill(&mut nonce_bytes).unwrap(); let nonce = Nonce::assume_unique_for_key(nonce_bytes);
let mut ciphertext = plaintext.to_vec(); key.seal_in_place_append_tag(nonce, Aad::empty(), &mut ciphertext) .unwrap();
// Prepend nonce to ciphertext let mut result = nonce_bytes.to_vec(); result.extend_from_slice(&ciphertext); result}
fn decrypt(key_bytes: &[u8; 32], data: &[u8]) -> Option<Vec<u8>> { if data.len() < 12 { return None; }
let (nonce_bytes, ciphertext) = data.split_at(12); let nonce_array: [u8; 12] = nonce_bytes.try_into().ok()?; let nonce = Nonce::assume_unique_for_key(nonce_array);
let unbound_key = UnboundKey::new(&AES_256_GCM, key_bytes).ok()?; let key = LessSafeKey::new(unbound_key);
let mut plaintext = ciphertext.to_vec(); let decrypted = key.open_in_place(nonce, Aad::empty(), &mut plaintext).ok()?; Some(decrypted.to_vec())}That random nonce matters more than it looks. Underneath, GCM encrypts by XORing your data with a keystream made from the key and the nonce. Reuse both and you reuse the keystream, so XORing two ciphertexts cancels it out and leaves the XOR of the two plaintexts. The runner stands a toy keystream generator in for AES, since there are no crates to call, but the failure is the same one.
Key Derivation
Got cryptographically strong key material already? Use HKDF to spin off task-specific keys from it:
HKDF is NOT for passwords. HKDF is designed for deriving keys from key material that is already cryptographically strong (e.g., a Diffie-Hellman shared secret). For password-based key derivation, use PBKDF2 or Argon2, which are deliberately slow to resist brute-force attacks.
use ring::aead;use ring::hkdf;
fn derive_key(input_key_material: &[u8], salt: &[u8]) -> [u8; 32] { let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, salt); let prk = salt.extract(input_key_material);
let mut key = [0u8; 32]; let okm = prk.expand(&[b"encryption key"], &aead::AES_256_GCM) .expect("HKDF expand failed"); okm.fill(&mut key).expect("Key derivation failed"); key}Secure Random Number Generation
use ring::rand::{SecureRandom, SystemRandom};
fn generate_token() -> String { let rng = SystemRandom::new(); let mut bytes = [0u8; 32]; rng.fill(&mut bytes).expect("RNG failure"); hex_encode(&bytes)}
fn generate_nonce() -> [u8; 12] { let rng = SystemRandom::new(); let mut nonce = [0u8; 12]; rng.fill(&mut nonce).expect("RNG failure"); nonce}Constant-Time Comparisons
Comparing secrets (hashes, tokens, MACs) byte-by-byte will leak through how long the comparison takes. Attackers measure that:
use ring::constant_time;
fn verify_token(received: &[u8], expected: &[u8]) -> bool { // Constant-time comparison - takes the same time regardless of // where the first difference is. Prevents timing attacks. constant_time::verify_slices_are_equal(received, expected).is_ok()}
// WRONG: this leaks information through timingfn insecure_compare(a: &[u8], b: &[u8]) -> bool { if a.len() != b.len() { return false; } for i in 0..a.len() { if a[i] != b[i] { return false; } // Returns early - timing leak! } true}The runner times insecure_compare against a hand-rolled constant-time version on a 4 KB secret, moving the first wrong byte further along each time. The numbers vary between runs, but the insecure column should climb with the position while the constant-time one stays roughly level. An optimising compiler is free to rewrite a loop like the constant-time one, which is why real code uses ring::constant_time or the subtle crate rather than rolling its own.
Common Mistakes
- Using ECB mode: Identical plaintext blocks produce identical ciphertext. Use an authenticated mode such as AES-GCM or ChaCha20-Poly1305.
- Reusing nonces: AES-GCM nonces must be unique per key. Reuse destroys security. With random 96-bit nonces, NIST SP 800-38D (section 8.3) caps a key at 2^32 encryptions so the odds of a collision stay negligible; rotate keys well before that, or use a counter.
- Not authenticating: Encryption without authentication (HMAC or GCM) allows ciphertext modification.
- Hard-coded keys: Keys should come from secure key management, not source code.
- Using MD5/SHA1: These are broken for collision resistance. Use SHA-256 or SHA-3.
Practical Checklist
- Passwords: Argon2 (or bcrypt/scrypt)
- Encryption: AES-256-GCM (authenticated)
- Hashing: SHA-256 or SHA-3
- Random: the OS generator (
SystemRandom, orOsRngfromrand).rand'sthread_rngis a CSPRNG too, but the OS source is the safer default for keys - Comparison: Constant-time
- Key derivation: HKDF or PBKDF2
- Nonces: Never reuse, always random or counter-based