Search code examples
rustencryptioncryptography

How to decrypt ciphertext with rust ring AEAD?


I'm working on a simple POC for AEAD in ring. I'm trying to encrypt and decrypt a message with an AAD. I'm generating two random nonces, one for encryption and one for decryption. My understanding is that seal_in_place_append_tag() modifies in_out in place, encrypting the message therein and appending the tag. open_in_place() should take a ciphertext + tag and return a result containing the plaintext, right?

It seems like I'm doing things correctly but I'm getting an error when decrypting the message on line 24. Unfortunately, all of ring's errors are Unspecified which makes sense in production but is unhelpful in my case.

Any ideas? Here is my code:

use ring::aead::{UnboundKey, AES_256_GCM, LessSafeKey, NONCE_LEN, Aad, Nonce};
use ring::rand::{SystemRandom, SecureRandom};

fn main() {
    let mut secret = vec![0u8; AES_256_GCM.key_len()];
    let mut nonce_bytes = vec![0u8; NONCE_LEN];
    let mut nonce_bytes2 = vec![0u8; NONCE_LEN];
    let rng = SystemRandom::new();
    rng.fill(&mut secret).unwrap();
    rng.fill(&mut nonce_bytes).unwrap();
    rng.fill(&mut nonce_bytes2).unwrap();
    let nonce =  Nonce::try_assume_unique_for_key(&nonce_bytes).unwrap();
    let nonce2 = Nonce::try_assume_unique_for_key(&nonce_bytes2).unwrap();
    let key = LessSafeKey::new(UnboundKey::new(&AES_256_GCM, &secret).unwrap());
    let mut payload = Vec::from(String::from("Test"));
    let aad = Aad::from(b"test_aad");
    println!("{:?}", secret);
    println!("{:?}", aad);
    println!("{:?}", payload);
    key.seal_in_place_append_tag(nonce, aad, &mut payload).unwrap();
    println!("{:?}", secret);
    println!("{:?}", aad);
    println!("{:?}", payload);
    let key2 = LessSafeKey::new(UnboundKey::new(&AES_256_GCM, &secret).unwrap());
    key2.open_in_place(nonce2, aad, &mut payload).unwrap(); //Panics here
}

Solution

  • Solved this in the comments. The nonce used to seal the message must be used to open the message.