Coverage Report

Created: 2025-11-16 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/password-hash-0.4.2/src/output.rs
Line
Count
Source
1
//! Outputs from password hashing functions.
2
3
use crate::{Encoding, Error, Result};
4
use core::{cmp::PartialEq, fmt, str::FromStr};
5
use subtle::{Choice, ConstantTimeEq};
6
7
/// Output from password hashing functions, i.e. the "hash" or "digest"
8
/// as raw bytes.
9
///
10
/// The [`Output`] type implements the RECOMMENDED best practices described in
11
/// the [PHC string format specification][1], namely:
12
///
13
/// > The hash output, for a verification, must be long enough to make preimage
14
/// > attacks at least as hard as password guessing. To promote wide acceptance,
15
/// > a default output size of 256 bits (32 bytes, encoded as 43 characters) is
16
/// > recommended. Function implementations SHOULD NOT allow outputs of less
17
/// > than 80 bits to be used for password verification.
18
///
19
/// # Recommended length
20
/// Per the description above, the recommended default length for an [`Output`]
21
/// of a password hashing function is **32-bytes** (256-bits).
22
///
23
/// # Constraints
24
/// The above guidelines are interpreted into the following constraints:
25
///
26
/// - Minimum length: **10**-bytes (80-bits)
27
/// - Maximum length: **64**-bytes (512-bits)
28
///
29
/// The specific recommendation of a 64-byte maximum length is taken as a best
30
/// practice from the hash output guidelines for [Argon2 Encoding][2] given in
31
/// the same document:
32
///
33
/// > The hash output...length shall be between 12 and 64 bytes (16 and 86
34
/// > characters, respectively). The default output length is 32 bytes
35
/// > (43 characters).
36
///
37
/// Based on this guidance, this type enforces an upper bound of 64-bytes
38
/// as a reasonable maximum, and recommends using 32-bytes.
39
///
40
/// # Constant-time comparisons
41
/// The [`Output`] type impls the [`ConstantTimeEq`] trait from the [`subtle`]
42
/// crate and uses it to perform constant-time comparisons.
43
///
44
/// Additionally the [`PartialEq`] and [`Eq`] trait impls for [`Output`] use
45
/// [`ConstantTimeEq`] when performing comparisons.
46
///
47
/// ## Attacks on non-constant-time password hash comparisons
48
/// Comparing password hashes in constant-time is known to mitigate at least
49
/// one [poorly understood attack][3] involving an adversary with the following
50
/// knowledge/capabilities:
51
///
52
/// - full knowledge of what password hashing algorithm is being used
53
///   including any relevant configurable parameters
54
/// - knowledge of the salt for a particular victim
55
/// - ability to accurately measure a timing side-channel on comparisons
56
///   of the password hash over the network
57
///
58
/// An attacker with the above is able to perform an offline computation of
59
/// the hash for any chosen password in such a way that it will match the
60
/// hash computed by the server.
61
///
62
/// As noted above, they also measure timing variability in the server's
63
/// comparison of the hash it computes for a given password and a target hash
64
/// the attacker is trying to learn.
65
///
66
/// When the attacker observes a hash comparison that takes longer than their
67
/// previous attempts, they learn that they guessed another byte in the
68
/// password hash correctly. They can leverage repeated measurements and
69
/// observations with different candidate passwords to learn the password
70
/// hash a byte-at-a-time in a manner similar to other such timing side-channel
71
/// attacks.
72
///
73
/// The attack may seem somewhat counterintuitive since learning prefixes of a
74
/// password hash does not reveal any additional information about the password
75
/// itself. However, the above can be combined with an offline dictionary
76
/// attack where the attacker is able to determine candidate passwords to send
77
/// to the server by performing a brute force search offline and selecting
78
/// candidate passwords whose hashes match the portion of the prefix they have
79
/// learned so far.
80
///
81
/// As the attacker learns a longer and longer prefix of the password hash,
82
/// they are able to more effectively eliminate candidate passwords offline as
83
/// part of a dictionary attack, until they eventually guess the correct
84
/// password or exhaust their set of candidate passwords.
85
///
86
/// ## Mitigations
87
/// While we have taken care to ensure password hashes are compared in constant
88
/// time, we would also suggest preventing such attacks by using randomly
89
/// generated salts and keeping those salts secret.
90
///
91
/// The [`SaltString::generate`][`crate::SaltString::generate`] function can be
92
/// used to generate random high-entropy salt values.
93
///
94
/// [1]: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md#function-duties
95
/// [2]: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md#argon2-encoding
96
/// [3]: https://web.archive.org/web/20130208100210/http://security-assessment.com/files/documents/presentations/TimingAttackPresentation2012.pdf
97
#[derive(Copy, Clone, Eq)]
98
pub struct Output {
99
    /// Byte array containing a password hashing function output.
100
    bytes: [u8; Self::MAX_LENGTH],
101
102
    /// Length of the password hashing function output in bytes.
103
    length: u8,
104
105
    /// Encoding which output should be serialized with.
106
    encoding: Encoding,
107
}
108
109
#[allow(clippy::len_without_is_empty)]
110
impl Output {
111
    /// Minimum length of a [`Output`] string: 10-bytes.
112
    pub const MIN_LENGTH: usize = 10;
113
114
    /// Maximum length of [`Output`] string: 64-bytes.
115
    ///
116
    /// See type-level documentation about [`Output`] for more information.
117
    pub const MAX_LENGTH: usize = 64;
118
119
    /// Maximum length of [`Output`] when encoded as B64 string: 86-bytes
120
    /// (i.e. 86 ASCII characters)
121
    pub const B64_MAX_LENGTH: usize = ((Self::MAX_LENGTH * 4) / 3) + 1;
122
123
    /// Create a [`Output`] from the given byte slice, validating it according
124
    /// to [`Output::MIN_LENGTH`] and [`Output::MAX_LENGTH`] restrictions.
125
0
    pub fn new(input: &[u8]) -> Result<Self> {
126
0
        Self::init_with(input.len(), |bytes| {
127
0
            bytes.copy_from_slice(input);
128
0
            Ok(())
129
0
        })
130
0
    }
131
132
    /// Create a [`Output`] from the given byte slice and [`Encoding`],
133
    /// validating it according to [`Output::MIN_LENGTH`] and
134
    /// [`Output::MAX_LENGTH`] restrictions.
135
0
    pub fn new_with_encoding(input: &[u8], encoding: Encoding) -> Result<Self> {
136
0
        let mut result = Self::new(input)?;
137
0
        result.encoding = encoding;
138
0
        Ok(result)
139
0
    }
140
141
    /// Initialize an [`Output`] using the provided method, which is given
142
    /// a mutable byte slice into which it should write the output.
143
    ///
144
    /// The `output_size` (in bytes) must be known in advance, as well as at
145
    /// least [`Output::MIN_LENGTH`] bytes and at most [`Output::MAX_LENGTH`]
146
    /// bytes.
147
0
    pub fn init_with<F>(output_size: usize, f: F) -> Result<Self>
148
0
    where
149
0
        F: FnOnce(&mut [u8]) -> Result<()>,
150
    {
151
0
        if output_size < Self::MIN_LENGTH {
152
0
            return Err(Error::OutputTooShort);
153
0
        }
154
155
0
        if output_size > Self::MAX_LENGTH {
156
0
            return Err(Error::OutputTooLong);
157
0
        }
158
159
0
        let mut bytes = [0u8; Self::MAX_LENGTH];
160
0
        f(&mut bytes[..output_size])?;
161
162
0
        Ok(Self {
163
0
            bytes,
164
0
            length: output_size as u8,
165
0
            encoding: Encoding::default(),
166
0
        })
167
0
    }
168
169
    /// Borrow the output value as a byte slice.
170
0
    pub fn as_bytes(&self) -> &[u8] {
171
0
        &self.bytes[..self.len()]
172
0
    }
173
174
    /// Get the [`Encoding`] that this [`Output`] is serialized with.
175
0
    pub fn encoding(&self) -> Encoding {
176
0
        self.encoding
177
0
    }
178
179
    /// Get the length of the output value as a byte slice.
180
0
    pub fn len(&self) -> usize {
181
0
        usize::from(self.length)
182
0
    }
183
184
    /// Parse B64-encoded [`Output`], i.e. using the PHC string
185
    /// specification's restricted interpretation of Base64.
186
0
    pub fn b64_decode(input: &str) -> Result<Self> {
187
0
        Self::decode(input, Encoding::B64)
188
0
    }
189
190
    /// Write B64-encoded [`Output`] to the provided buffer, returning
191
    /// a sub-slice containing the encoded data.
192
    ///
193
    /// Returns an error if the buffer is too short to contain the output.
194
0
    pub fn b64_encode<'a>(&self, out: &'a mut [u8]) -> Result<&'a str> {
195
0
        self.encode(out, Encoding::B64)
196
0
    }
197
198
    /// Decode the given input string using the specified [`Encoding`].
199
0
    pub fn decode(input: &str, encoding: Encoding) -> Result<Self> {
200
0
        let mut bytes = [0u8; Self::MAX_LENGTH];
201
0
        encoding
202
0
            .decode(input, &mut bytes)
203
0
            .map_err(Into::into)
204
0
            .and_then(|decoded| Self::new_with_encoding(decoded, encoding))
205
0
    }
206
207
    /// Encode this [`Output`] using the specified [`Encoding`].
208
0
    pub fn encode<'a>(&self, out: &'a mut [u8], encoding: Encoding) -> Result<&'a str> {
209
0
        Ok(encoding.encode(self.as_ref(), out)?)
210
0
    }
211
212
    /// Get the length of this [`Output`] when encoded as B64.
213
0
    pub fn b64_len(&self) -> usize {
214
0
        Encoding::B64.encoded_len(self.as_ref())
215
0
    }
216
}
217
218
impl AsRef<[u8]> for Output {
219
0
    fn as_ref(&self) -> &[u8] {
220
0
        self.as_bytes()
221
0
    }
222
}
223
224
impl ConstantTimeEq for Output {
225
0
    fn ct_eq(&self, other: &Self) -> Choice {
226
0
        self.as_ref().ct_eq(other.as_ref())
227
0
    }
228
}
229
230
impl FromStr for Output {
231
    type Err = Error;
232
233
0
    fn from_str(s: &str) -> Result<Self> {
234
0
        Self::b64_decode(s)
235
0
    }
236
}
237
238
impl PartialEq for Output {
239
0
    fn eq(&self, other: &Self) -> bool {
240
0
        self.ct_eq(other).into()
241
0
    }
242
}
243
244
impl TryFrom<&[u8]> for Output {
245
    type Error = Error;
246
247
0
    fn try_from(input: &[u8]) -> Result<Output> {
248
0
        Self::new(input)
249
0
    }
250
}
251
252
impl fmt::Display for Output {
253
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254
0
        let mut buffer = [0u8; Self::B64_MAX_LENGTH];
255
0
        self.encode(&mut buffer, self.encoding)
256
0
            .map_err(|_| fmt::Error)
257
0
            .and_then(|encoded| f.write_str(encoded))
258
0
    }
259
}
260
261
impl fmt::Debug for Output {
262
0
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263
0
        write!(f, "Output(\"{}\")", self)
264
0
    }
265
}
266
267
#[cfg(test)]
268
mod tests {
269
    use super::{Error, Output};
270
271
    #[test]
272
    fn new_with_valid_min_length_input() {
273
        let bytes = [10u8; 10];
274
        let output = Output::new(&bytes).unwrap();
275
        assert_eq!(output.as_ref(), &bytes);
276
    }
277
278
    #[test]
279
    fn new_with_valid_max_length_input() {
280
        let bytes = [64u8; 64];
281
        let output = Output::new(&bytes).unwrap();
282
        assert_eq!(output.as_ref(), &bytes);
283
    }
284
285
    #[test]
286
    fn reject_new_too_short() {
287
        let bytes = [9u8; 9];
288
        let err = Output::new(&bytes).err().unwrap();
289
        assert_eq!(err, Error::OutputTooShort);
290
    }
291
292
    #[test]
293
    fn reject_new_too_long() {
294
        let bytes = [65u8; 65];
295
        let err = Output::new(&bytes).err().unwrap();
296
        assert_eq!(err, Error::OutputTooLong);
297
    }
298
299
    #[test]
300
    fn partialeq_true() {
301
        let a = Output::new(&[1u8; 32]).unwrap();
302
        let b = Output::new(&[1u8; 32]).unwrap();
303
        assert_eq!(a, b);
304
    }
305
306
    #[test]
307
    fn partialeq_false() {
308
        let a = Output::new(&[1u8; 32]).unwrap();
309
        let b = Output::new(&[2u8; 32]).unwrap();
310
        assert_ne!(a, b);
311
    }
312
}