Skip to content

Instantly share code, notes, and snippets.

@ambiso
Created May 2, 2023 18:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ambiso/254290fd74497ad34224dd49f8d10dd9 to your computer and use it in GitHub Desktop.
Save ambiso/254290fd74497ad34224dd49f8d10dd9 to your computer and use it in GitHub Desktop.
rust ring aead example
use ring::aead;
use ring::aead::BoundKey;
use ring::error::Unspecified;
use ring::rand::SecureRandom;
use ring::rand::SystemRandom;
pub struct NonceGenerator {
last_nonce: u64,
}
impl NonceGenerator {
fn new() -> Self {
Self { last_nonce: 0 }
}
}
impl aead::NonceSequence for NonceGenerator {
fn advance(&mut self) -> Result<aead::Nonce, Unspecified> {
self.last_nonce += self.last_nonce.checked_add(1).ok_or(Unspecified)?;
let mut nonce = [0u8; 12];
(&mut nonce[0..8]).copy_from_slice(&self.last_nonce.to_le_bytes()); // 0 guarantees that this is correct lmao
Ok(aead::Nonce::assume_unique_for_key(nonce))
}
}
pub fn make_sealing_key(key: &[u8]) -> Result<aead::SealingKey<NonceGenerator>, Unspecified> {
Ok(aead::SealingKey::new(
aead::UnboundKey::new(&aead::AES_256_GCM, key)?,
NonceGenerator::new(),
))
}
pub fn make_opening_key(key: &[u8]) -> Result<aead::OpeningKey<NonceGenerator>, Unspecified> {
Ok(aead::OpeningKey::new(
aead::UnboundKey::new(&aead::AES_256_GCM, key)?,
NonceGenerator::new(),
))
}
fn main() -> Result<(), Unspecified> {
let mut k = [0u8; 32]; // you MUST not use k to create two SealingKey instances with the nonce generator, otherwise you'll re-use the same nonce!
SystemRandom::new().fill(&mut k)?;
let mut sk = make_sealing_key(&k)?;
let mut inout = b"Yellow submarine".to_vec();
let aad = b"Some additional data you want authenticated, like some context e.g. who is sending stuff to whom";
sk.seal_in_place_append_tag(aead::Aad::from(aad), &mut inout)?;
let mut ok = make_opening_key(&k)?;
let result = ok.open_in_place(aead::Aad::from(aad), &mut inout)?;
assert_eq!(result, b"Yellow submarine".to_vec());
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment