use crate::protected::Protected;
use rand::{prelude::ThreadRng, RngCore};
pub const BLOCK_SIZE: usize = 1_048_576;
pub const SALT_LEN: usize = 16;
pub const MASTER_KEY_LEN: usize = 32;
pub const ENCRYPTED_MASTER_KEY_LEN: usize = 48;
pub const ALGORITHMS_LEN: usize = 3;
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Algorithm {
Aes256Gcm,
XChaCha20Poly1305,
DeoxysII256,
}
pub static ALGORITHMS: [Algorithm; ALGORITHMS_LEN] = [
Algorithm::XChaCha20Poly1305,
Algorithm::Aes256Gcm,
Algorithm::DeoxysII256,
];
impl std::fmt::Display for Algorithm {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Algorithm::Aes256Gcm => write!(f, "AES-256-GCM"),
Algorithm::XChaCha20Poly1305 => write!(f, "XChaCha20-Poly1305"),
Algorithm::DeoxysII256 => write!(f, "Deoxys-II-256"),
}
}
}
#[derive(PartialEq, Eq)]
pub enum Mode {
MemoryMode,
StreamMode,
}
impl std::fmt::Display for Mode {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Mode::MemoryMode => write!(f, "Memory Mode"),
Mode::StreamMode => write!(f, "Stream Mode"),
}
}
}
#[must_use]
pub fn gen_nonce(algorithm: &Algorithm, mode: &Mode) -> Vec<u8> {
let nonce_len = get_nonce_len(algorithm, mode);
let mut nonce = vec![0u8; nonce_len];
ThreadRng::default().fill_bytes(&mut nonce);
nonce
}
#[must_use]
pub fn get_nonce_len(algorithm: &Algorithm, mode: &Mode) -> usize {
let mut nonce_len = match algorithm {
Algorithm::Aes256Gcm => 12,
Algorithm::XChaCha20Poly1305 => 24,
Algorithm::DeoxysII256 => 15,
};
if mode == &Mode::StreamMode {
nonce_len -= 4;
}
nonce_len
}
#[must_use]
pub fn gen_master_key() -> Protected<[u8; MASTER_KEY_LEN]> {
let mut master_key = [0u8; MASTER_KEY_LEN];
ThreadRng::default().fill_bytes(&mut master_key);
Protected::new(master_key)
}
#[must_use]
pub fn gen_salt() -> [u8; SALT_LEN] {
let mut salt = [0u8; SALT_LEN];
ThreadRng::default().fill_bytes(&mut salt);
salt
}