use crypto::Error; use crypto::ciphers::{ aes_gcm::Aes256Gcm, traits::Aead, }; use crypto::utils::rand; /// A nonce used for encrypting the gallery's index, as well as all full images pub const NONCE_A: [u8; 12] = [0xd0, 0xc3, 0x75, 0x56, 0x58, 0xc1, 0x7e, 0x5f, 0xd6, 0xcc, 0xb6, 0x76]; /// A nonce used for encrypting all thumbnails pub const NONCE_B: [u8; 12] = [0x77, 0xe7, 0xf7, 0x64, 0x33, 0x80, 0x25, 0x49, 0xec, 0xef, 0x57, 0x3f]; pub fn encrypt(key: &[u8; 32], nonce: &[u8; 12], plaintext: &[u8]) -> Vec { let mut result = vec![0; plaintext.len() + 16]; let (cyphertext, tag) = result.split_at_mut(plaintext.len()); Aes256Gcm::try_encrypt( key, nonce, &[], plaintext, cyphertext, tag).expect("Unexpected cryptography error"); result } pub fn decrypt<'p>(key: &[u8; 32], nonce: &[u8; 12], encrypted: &[u8], plaintext_dest: &'p mut Vec) -> Option<&'p mut Vec> { let (cyphertext, tag) = encrypted.split_at(encrypted.len() - 16); plaintext_dest.resize(cyphertext.len(), 0); let e = Aes256Gcm::try_decrypt( key, nonce, &[], plaintext_dest, cyphertext, tag); match e { Ok(_) => Some(plaintext_dest), Err(Error::CipherError { alg: "AES-256-GCM" }) => None, // Invalid key or tag Err(e) => panic!("Unexpected decryption return value: {e:?}"), } } pub fn make_key() -> [u8; 32] { let mut result = [0; 32]; rand::fill(&mut result).expect("Unexpected error generating random data"); result }