dcrypt_algorithms/kdf/
common.rs1#![cfg_attr(not(feature = "std"), no_std)]
4
5#[cfg(feature = "alloc")]
7extern crate alloc;
8
9#[cfg(feature = "std")]
10use std::vec::Vec;
11
12#[cfg(all(feature = "alloc", not(feature = "std")))]
13use alloc::vec::Vec;
14
15use subtle::ConstantTimeEq;
16use zeroize::Zeroizing;
17
18#[cfg(feature = "std")]
20use rand::{rngs::OsRng, RngCore};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
24pub enum SecurityLevel {
25 L128,
27 L192,
29 L256,
31 Custom(u32),
33}
34
35impl SecurityLevel {
36 pub fn bits(&self) -> u32 {
38 match self {
39 SecurityLevel::L128 => 128,
40 SecurityLevel::L192 => 192,
41 SecurityLevel::L256 => 256,
42 SecurityLevel::Custom(bits) => *bits,
43 }
44 }
45
46 pub fn recommended_output_size(&self) -> usize {
48 (self.bits() / 4) as usize
51 }
52
53 pub fn meets_minimum(&self, minimum: SecurityLevel) -> bool {
55 self.bits() >= minimum.bits()
56 }
57}
58
59#[inline]
61pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
62 if a.len() != b.len() {
63 return false;
64 }
65 a.ct_eq(b).into()
66}
67
68#[cfg(feature = "std")]
70pub fn generate_salt(len: usize) -> Zeroizing<Vec<u8>> {
71 let mut salt = vec![0u8; len];
72 OsRng.fill_bytes(&mut salt);
73 Zeroizing::new(salt)
74}
75
76#[cfg(all(feature = "alloc", not(feature = "std"), not(target_arch = "wasm32")))]
80pub fn generate_salt(len: usize) -> Zeroizing<Vec<u8>> {
81 let mut salt = vec![0u8; len];
84
85 Zeroizing::new(salt)
90}
91
92#[cfg(all(feature = "alloc", target_arch = "wasm32", not(feature = "std")))]
94pub fn generate_salt(len: usize) -> Zeroizing<Vec<u8>> {
95 let mut salt = vec![0u8; len];
96
97 getrandom::getrandom(&mut salt).expect("Failed to generate random bytes");
99
100 Zeroizing::new(salt)
101}