volaris_tools/
utils.rs

1// TODO(pleshevskiy): dedup these utils
2use std::fmt::Write;
3
4#[cfg(test)]
5mod test {
6    use corecrypto::primitives::{get_nonce_len, Algorithm, Mode, MASTER_KEY_LEN, SALT_LEN};
7    use corecrypto::protected::Protected;
8    use rand::{prelude::StdRng, RngCore, SeedableRng};
9
10    const SALT_SEED: u64 = 123_456;
11    const NONCE_SEED: u64 = SALT_SEED + 1;
12    const MASTER_KEY_SEED: u64 = NONCE_SEED + 2;
13
14    #[must_use]
15    pub fn gen_salt() -> [u8; SALT_LEN] {
16        let mut salt = [0u8; SALT_LEN];
17        StdRng::seed_from_u64(SALT_SEED).fill_bytes(&mut salt);
18        salt
19    }
20
21    #[must_use]
22    pub fn gen_nonce(algorithm: &Algorithm, mode: &Mode) -> Vec<u8> {
23        let nonce_len = get_nonce_len(algorithm, mode);
24        let mut nonce = vec![0u8; nonce_len];
25        StdRng::seed_from_u64(NONCE_SEED).fill_bytes(&mut nonce);
26        nonce
27    }
28
29    #[must_use]
30    pub fn gen_master_key() -> Protected<[u8; MASTER_KEY_LEN]> {
31        let mut master_key = [0u8; MASTER_KEY_LEN];
32        StdRng::seed_from_u64(MASTER_KEY_SEED).fill_bytes(&mut master_key);
33        Protected::new(master_key)
34    }
35}
36
37#[must_use]
38pub fn hex_encode(bytes: &[u8]) -> String {
39    let mut result = String::new();
40    for byte in bytes {
41        write!(result, "{byte:02x}").unwrap();
42    }
43    result
44}
45
46#[cfg(test)]
47pub use test::gen_master_key;
48#[cfg(test)]
49pub use test::gen_nonce;
50#[cfg(test)]
51pub use test::gen_salt;
52
53#[cfg(not(test))]
54pub use corecrypto::primitives::gen_master_key;
55#[cfg(not(test))]
56pub use corecrypto::primitives::gen_nonce;
57#[cfg(not(test))]
58pub use corecrypto::primitives::gen_salt;