Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Created July 12, 2023 20:15
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 jedisct1/d825e85ac0043bce260be5c0b3a307a1 to your computer and use it in GitHub Desktop.
Save jedisct1/d825e85ac0043bce260be5c0b3a307a1 to your computer and use it in GitHub Desktop.
use aegis::aegis128l::Aegis128L;
const ENCRYPTED_MESSAGE_PREFIX: &[u8] = b"E:aegis128l:";
pub fn encrypt_message(data: &[u8], key: &[u8; 16]) -> Result<Vec<u8>, getrandom::Error> {
let mut nonce = [0; 16];
getrandom::getrandom(&mut nonce)?;
let cipher = Aegis128L::<32>::new(key, &nonce);
let (encrypted, tag) = cipher.encrypt(data, &[]);
let mut out = Vec::new();
out.extend(ENCRYPTED_MESSAGE_PREFIX);
out.extend(&nonce);
out.extend(&encrypted);
out.extend(&tag);
Ok(out)
}
#[derive(Debug)]
pub enum DecryptError {
UnsupportedAlgorithm,
BadFormat,
InvalidData,
}
pub fn decrypt_message(data: &[u8], key: &[u8; 16]) -> Result<Vec<u8>, DecryptError> {
let data = match data.strip_prefix(ENCRYPTED_MESSAGE_PREFIX) {
Some(v) => v,
None => return Err(DecryptError::UnsupportedAlgorithm),
};
// data must be prefixed with a 16 byte nonce and suffixed with a 16 byte tag
if data.len() < 48 {
return Err(DecryptError::BadFormat);
}
let mut nonce = [0; 16];
nonce.copy_from_slice(&data[..16]);
let encrypted = &data[16..(data.len() - 32)];
let mut tag = [0; 32];
tag.copy_from_slice(&data[(data.len() - 32)..]);
let cipher = Aegis128L::<32>::new(key, &nonce);
let plain = match cipher.decrypt(encrypted, &tag, &[]) {
Ok(v) => v,
Err(_) => return Err(DecryptError::InvalidData),
};
Ok(plain)
}
fn main() {
let key = b"0123456789abcdef";
let data = "Hello, world!".as_bytes();
let ct = encrypt_message(data, key).unwrap();
let pt = decrypt_message(&ct, key).unwrap();
println!("{}", std::str::from_utf8(&pt).unwrap());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment