FAQ - Help and questions

How do I encrypt data in Rust, and why must I use authenticated encryption?

#security#encryption#aes-gcmpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Use an authenticated encryption (AEAD) cipher such as AES-256-GCM from the aes-gcm crate, with a random key kept outside the code and a new random nonce for every message, stored beside the ciphertext. A changed ciphertext then fails to decrypt. Never reuse a nonce with the same key.

Checked with rustc 1.93.0, aes-gcm 0.10.3, Windows 11 (release build)

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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:

  1. The key is random, secret and stored outside the source code (see the thread on secrets).
  2. 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.
Cargo.tomltoml
[dependencies]
aes-gcm = "0.10"
src/main.rsrust
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"));
}
text
round trip: Some("card ending 4242")
tampered:   None
same input twice differs: true

The 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#

  1. Generate the key once with a secure generator, and store it in a secret manager or protected file.
  2. Prefix each message with its nonce, as above, and decrypt from that.
  3. 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.
  4. Plan key rotation: store a key identifier beside the ciphertext.
  5. 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).

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet