use aes_gcm::{
Aes128Gcm,
aead::{Generate, Key},
};
pub struct CipherGeneration {}
impl CipherGeneration {
pub fn random_iv() -> Vec<u8> {
Self::random_bytes(12)
}
pub fn random_key() -> String {
let key = Key::<Aes128Gcm>::generate();
hex::encode(key)
}
fn random_bytes(length: usize) -> Vec<u8> {
let mut data = vec![0; length];
getrandom::fill(&mut data).expect("failed to read random bytes from the operating system");
data
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_random_iv() {
let first_random_iv = CipherGeneration::random_iv();
let second_random_iv = CipherGeneration::random_iv();
assert_ne!(first_random_iv, second_random_iv);
}
#[test]
fn test_random_key() {
let first_random_key = CipherGeneration::random_key();
let second_random_key = CipherGeneration::random_key();
assert_ne!(first_random_key, second_random_key);
}
#[test]
fn test_random_bytes() {
let first_random_bytes = CipherGeneration::random_bytes(10);
let second_random_bytes = CipherGeneration::random_bytes(10);
assert_ne!(first_random_bytes, second_random_bytes);
}
}