1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use crate::{Error, KdfAlg, Result};
use encoding::{CheckedSum, Decode, Encode, Reader, Writer};
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "encryption")]
use {
crate::Cipher,
bcrypt_pbkdf::bcrypt_pbkdf,
rand_core::{CryptoRng, RngCore},
zeroize::Zeroizing,
};
#[cfg(feature = "encryption")]
const DEFAULT_BCRYPT_ROUNDS: u32 = 16;
#[cfg(feature = "encryption")]
const DEFAULT_SALT_SIZE: usize = 16;
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Kdf {
None,
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
Bcrypt {
salt: Vec<u8>,
rounds: u32,
},
}
impl Kdf {
#[cfg(feature = "encryption")]
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub fn new(algorithm: KdfAlg, mut rng: impl CryptoRng + RngCore) -> Result<Self> {
let mut salt = vec![0u8; DEFAULT_SALT_SIZE];
rng.fill_bytes(&mut salt);
match algorithm {
KdfAlg::None => {
Err(Error::Algorithm)
}
KdfAlg::Bcrypt => Ok(Kdf::Bcrypt {
salt,
rounds: DEFAULT_BCRYPT_ROUNDS,
}),
}
}
pub fn algorithm(&self) -> KdfAlg {
match self {
Self::None => KdfAlg::None,
#[cfg(feature = "alloc")]
Self::Bcrypt { .. } => KdfAlg::Bcrypt,
}
}
#[cfg(feature = "encryption")]
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub fn derive(&self, password: impl AsRef<[u8]>, output: &mut [u8]) -> Result<()> {
match self {
Kdf::None => Err(Error::Decrypted),
Kdf::Bcrypt { salt, rounds } => {
bcrypt_pbkdf(password, salt, *rounds, output).map_err(|_| Error::Crypto)?;
Ok(())
}
}
}
#[cfg(feature = "encryption")]
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub fn derive_key_and_iv(
&self,
cipher: Cipher,
password: impl AsRef<[u8]>,
) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)> {
let (key_size, iv_size) = cipher.key_and_iv_size().ok_or(Error::Decrypted)?;
let okm_size = key_size
.checked_add(iv_size)
.ok_or(encoding::Error::Length)?;
let mut okm = Zeroizing::new(vec![0u8; okm_size]);
self.derive(password, &mut okm)?;
let iv = okm.split_off(key_size);
Ok((okm, iv))
}
pub fn is_none(&self) -> bool {
self == &Self::None
}
pub fn is_some(&self) -> bool {
!self.is_none()
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn is_bcrypt(&self) -> bool {
matches!(self, Self::Bcrypt { .. })
}
}
impl Default for Kdf {
fn default() -> Self {
Self::None
}
}
impl Decode for Kdf {
type Error = Error;
fn decode(reader: &mut impl Reader) -> Result<Self> {
match KdfAlg::decode(reader)? {
KdfAlg::None => {
if usize::decode(reader)? == 0 {
Ok(Self::None)
} else {
Err(Error::Algorithm)
}
}
KdfAlg::Bcrypt => {
#[cfg(not(feature = "alloc"))]
return Err(Error::Algorithm);
#[cfg(feature = "alloc")]
reader.read_prefixed(|reader| {
Ok(Self::Bcrypt {
salt: Vec::decode(reader)?,
rounds: u32::decode(reader)?,
})
})
}
}
}
}
impl Encode for Kdf {
type Error = Error;
fn encoded_len(&self) -> Result<usize> {
let kdfopts_prefixed_len = match self {
Self::None => 4,
#[cfg(feature = "alloc")]
Self::Bcrypt { salt, .. } => [12, salt.len()].checked_sum()?,
};
Ok([self.algorithm().encoded_len()?, kdfopts_prefixed_len].checked_sum()?)
}
fn encode(&self, writer: &mut impl Writer) -> Result<()> {
self.algorithm().encode(writer)?;
match self {
Self::None => 0usize.encode(writer)?,
#[cfg(feature = "alloc")]
Self::Bcrypt { salt, rounds } => {
[8, salt.len()].checked_sum()?.encode(writer)?;
salt.encode(writer)?;
rounds.encode(writer)?
}
}
Ok(())
}
}