1use crate::{Error, KdfAlg, Result};
6use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
7
8#[cfg(feature = "alloc")]
9use alloc::vec::Vec;
10
11#[cfg(feature = "encryption")]
12use {crate::Cipher, bcrypt_pbkdf::bcrypt_pbkdf, rand_core::TryCryptoRng, zeroize::Zeroizing};
13
14#[cfg(feature = "encryption")]
17const DEFAULT_BCRYPT_ROUNDS: u32 = 32;
18
19#[cfg(feature = "alloc")]
22const MAX_BCRYPT_ROUNDS: u32 = 1 << 20;
23
24#[cfg(feature = "encryption")]
26const DEFAULT_SALT_SIZE: usize = 16;
27
28#[derive(Clone, Debug, Eq, PartialEq)]
30#[non_exhaustive]
31#[derive(Default)]
32pub enum Kdf {
33 #[default]
35 None,
36
37 #[cfg(feature = "alloc")]
39 Bcrypt {
40 salt: Vec<u8>,
42
43 rounds: u32,
45 },
46}
47
48impl Kdf {
49 #[cfg(feature = "encryption")]
54 pub fn new<R: TryCryptoRng + ?Sized>(algorithm: KdfAlg, rng: &mut R) -> Result<Self> {
55 let mut salt = vec![0u8; DEFAULT_SALT_SIZE];
56 rng.try_fill_bytes(&mut salt)
57 .map_err(|_| Error::RngFailure)?;
58
59 match algorithm {
60 KdfAlg::None => {
61 Err(Error::AlgorithmUnknown)
63 }
64 KdfAlg::Bcrypt => Ok(Kdf::Bcrypt {
65 salt,
66 rounds: DEFAULT_BCRYPT_ROUNDS,
67 }),
68 }
69 }
70
71 #[must_use]
73 pub fn algorithm(&self) -> KdfAlg {
74 match self {
75 Self::None => KdfAlg::None,
76 #[cfg(feature = "alloc")]
77 Self::Bcrypt { .. } => KdfAlg::Bcrypt,
78 }
79 }
80
81 #[cfg(feature = "encryption")]
87 pub fn derive(&self, password: impl AsRef<[u8]>, output: &mut [u8]) -> Result<()> {
88 match self {
89 Kdf::None => Err(Error::Decrypted),
90 Kdf::Bcrypt { salt, rounds } => {
91 validate_bcrypt_rounds(*rounds)?;
92 bcrypt_pbkdf(password, salt, *rounds, output).map_err(|_| Error::Crypto)?;
93 Ok(())
94 }
95 }
96 }
97
98 #[cfg(feature = "encryption")]
107 pub fn derive_key_and_iv(
108 &self,
109 cipher: Cipher,
110 password: impl AsRef<[u8]>,
111 ) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)> {
112 let (key_size, iv_size) = cipher.key_and_iv_size().ok_or(Error::Decrypted)?;
113
114 let okm_size = key_size
115 .checked_add(iv_size)
116 .ok_or(encoding::Error::Length)?;
117
118 let mut okm = Zeroizing::new(vec![0u8; okm_size]);
119 self.derive(password, &mut okm)?;
120 let mut iv = okm.split_off(key_size);
121
122 if cipher == Cipher::ChaCha20Poly1305 {
126 iv.copy_from_slice(&cipher::ChaChaNonce::default());
127 }
128
129 Ok((okm, iv))
130 }
131
132 #[must_use]
134 pub fn is_none(&self) -> bool {
135 self == &Self::None
136 }
137
138 #[must_use]
140 pub fn is_some(&self) -> bool {
141 !self.is_none()
142 }
143
144 #[cfg(feature = "alloc")]
146 #[must_use]
147 pub fn is_bcrypt(&self) -> bool {
148 matches!(self, Self::Bcrypt { .. })
149 }
150}
151
152impl Decode for Kdf {
153 type Error = Error;
154
155 fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
156 match KdfAlg::decode(reader)? {
157 KdfAlg::None => {
158 if usize::decode(reader)? == 0 {
159 Ok(Self::None)
160 } else {
161 Err(Error::AlgorithmUnknown)
162 }
163 }
164 KdfAlg::Bcrypt => {
165 #[cfg(not(feature = "alloc"))]
166 return Err(Error::AlgorithmUnknown);
167
168 #[cfg(feature = "alloc")]
169 reader.read_prefixed(|reader| {
170 let salt = Vec::decode(reader)?;
171 let rounds = u32::decode(reader)?;
172 validate_bcrypt_rounds(rounds)?;
173 Ok(Self::Bcrypt { salt, rounds })
174 })
175 }
176 }
177 }
178}
179
180impl Encode for Kdf {
181 fn encoded_len(&self) -> encoding::Result<usize> {
182 let kdfopts_prefixed_len = match self {
183 Self::None => 4,
184 #[cfg(feature = "alloc")]
185 Self::Bcrypt { salt, rounds } => {
186 validate_bcrypt_rounds(*rounds).map_err(|_| encoding::Error::Overflow)?;
187 [12, salt.len()].checked_sum()?
188 }
189 };
190
191 [self.algorithm().encoded_len()?, kdfopts_prefixed_len].checked_sum()
192 }
193
194 fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
195 self.encoded_len()?;
197 self.algorithm().encode(writer)?;
198
199 match self {
200 Self::None => 0usize.encode(writer)?,
201 #[cfg(feature = "alloc")]
202 Self::Bcrypt { salt, rounds } => {
203 [8, salt.len()].checked_sum()?.encode(writer)?;
204 salt.encode(writer)?;
205 rounds.encode(writer)?;
206 }
207 }
208
209 Ok(())
210 }
211}
212
213#[cfg(feature = "alloc")]
215fn validate_bcrypt_rounds(rounds: u32) -> Result<()> {
216 if !(1..=MAX_BCRYPT_ROUNDS).contains(&rounds) {
217 return Err(Error::Crypto);
218 }
219 Ok(())
220}
221
222#[cfg(all(test, feature = "alloc"))]
223mod tests {
224 use super::{Kdf, MAX_BCRYPT_ROUNDS};
225 use crate::Error;
226 use alloc::vec::Vec;
227 use encoding::{Decode, Decoder, Encode};
228
229 #[test]
230 fn bcrypt_rounds_boundaries() {
231 let mut encoded = Kdf::Bcrypt {
232 salt: b"salt".to_vec(),
233 rounds: 1,
234 }
235 .encode_vec()
236 .unwrap();
237
238 for (rounds, valid) in [
239 (0, false),
240 (1, true),
241 (MAX_BCRYPT_ROUNDS, true),
242 (MAX_BCRYPT_ROUNDS + 1, false),
243 (u32::MAX, false),
244 ] {
245 let kdf = Kdf::Bcrypt {
246 salt: b"salt".to_vec(),
247 rounds,
248 };
249 let offset = encoded.len() - 4;
251 encoded[offset..].copy_from_slice(&rounds.to_be_bytes());
252
253 let mut output = Vec::new();
254 let expected = if valid {
255 assert_eq!(kdf.encoded_len(), Ok(encoded.len()));
256 kdf.encode(&mut output).unwrap();
257 assert_eq!(output, encoded);
258 Ok(kdf)
259 } else {
260 assert_eq!(kdf.encoded_len(), Err(encoding::Error::Overflow));
261 assert_eq!(kdf.encode(&mut output), Err(encoding::Error::Overflow));
262 assert!(output.is_empty());
263 Err(Error::Crypto)
264 };
265 let mut decoder = Decoder::from_bytes(&encoded).unwrap();
266 assert_eq!(Kdf::decode(&mut decoder), expected, "rounds: {rounds}");
267 if valid {
268 decoder.finish(()).unwrap();
269 }
270 }
271 }
272
273 #[cfg(feature = "encryption")]
274 #[test]
275 fn derive_bcrypt_invalid_rounds() {
276 struct UnreadPassword;
278
279 impl AsRef<[u8]> for UnreadPassword {
280 fn as_ref(&self) -> &[u8] {
281 panic!("invalid rounds must be rejected before accessing the password");
282 }
283 }
284
285 for rounds in [0, MAX_BCRYPT_ROUNDS + 1, u32::MAX] {
286 let kdf = Kdf::Bcrypt {
287 salt: b"salt".to_vec(),
288 rounds,
289 };
290 let mut output = [0xa5; 32];
291 assert_eq!(kdf.derive(UnreadPassword, &mut output), Err(Error::Crypto));
292 assert_eq!(output, [0xa5; 32]);
293 }
294 }
295}