pqbox 1.1.0

Post-quantum crypto toolkit: hybrid ML-KEM-1024 + P-384 sealed boxes, composite ML-DSA-87 signatures, an opt-in paranoid suite adding Classic McEliece and SLH-DSA, AEAD, KDF, hashing and Argon2id
Documentation
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! Argon2id (`argon2`, RFC 9106): password hashing to PHC strings such as
//! `$argon2id$v=19$m=65536,t=3,p=1$<salt>$<hash>`, and key derivation from a password and a
//! stored salt.
//!
//! # Key derivation
//!
//! [`derive_key`] is raw Argon2id (version 0x13, no secret, no associated data) of a password and
//! a salt the application stores next to what it encrypts: the same password, salt, costs and
//! length always give the same key, so the key can be derived again later instead of being
//! stored. It is the `Argon2id(password, salt, m, t, p, length)` of RFC 9106 and of other Argon2
//! libraries (`argon2`'s `hash_password_into`, argon2-cffi's `hash_secret_raw`, Node's
//! `crypto.argon2`), so keys derived elsewhere with the same inputs match.
//!
//! - The salt must be at least [`MIN_SALT_LEN`] (16) bytes; [`generate_salt`] makes a random one.
//!   Use a fresh salt for every password and purpose, and store it with the data.
//! - The costs default to those of [`hash_password`] (64 MiB, 3 passes, 1 lane) and are checked
//!   against [`Limits::DEFAULT`] (256 MiB, 10 passes, 8 lanes) before anything is allocated, as
//!   in [`verify_password`]. Costs stored with the data come from whoever wrote it:
//!   [`derive_key_with_limits`] accepts higher ones on purpose.
//! - Keys are [`MIN_KEY_LEN`] (16) to [`MAX_KEY_LEN`] (64) bytes, 32 by default. For several
//!   keys, derive one and expand it with [`crate::kdf::hkdf_sha256`], one `info` label per key.
//! - Domain separation: Argon2id has no context input here, so the output depends only on the
//!   password, the salt, the costs and the length. Keep keys for different purposes apart with
//!   distinct salts, or with distinct HKDF labels on top of one derived key; never reuse one
//!   derived key for two purposes directly.

use argon2::password_hash::phc::PasswordHash;
use argon2::{Algorithm, Argon2, PasswordHasher, PasswordVerifier, Version};
use zeroize::{ZeroizeOnDrop, Zeroizing};

use crate::{Error, Result, Rng};

/// Default memory cost: 64 MiB (in KiB).
pub const DEFAULT_M_COST: u32 = 64 * 1024;
/// Default time cost (passes).
pub const DEFAULT_T_COST: u32 = 3;
/// Default parallelism.
pub const DEFAULT_P_COST: u32 = 1;
/// Salt length of [`hash_password`] and [`generate_salt`].
pub const SALT_LEN: usize = 16;
/// Shortest salt [`derive_key`] accepts (128 bits, as RFC 9106 recommends).
pub const MIN_SALT_LEN: usize = 16;
/// Shortest key [`derive_key`] derives.
pub const MIN_KEY_LEN: usize = 16;
/// Longest key [`derive_key`] derives. For more key material, expand a derived key with
/// [`crate::kdf::hkdf_sha256`].
pub const MAX_KEY_LEN: usize = 64;
/// Default length of a derived key.
pub const DEFAULT_KEY_LEN: usize = 32;
/// The most memory (256 MiB, in KiB) [`verify_password`] and [`hash_password`] agree to spend.
///
/// The costs of a PHC string come from whoever wrote it, so they are capped before any memory is
/// allocated: at the caps, one verification takes about 256 MiB and on the order of a second
/// of CPU (Argon2id cost grows with `m_cost * t_cost`). Use [`verify_password_with_limits`] to
/// accept more expensive hashes on purpose.
pub const MAX_M_COST: u32 = 256 * 1024;
/// The most passes [`verify_password`] and [`hash_password`] agree to run.
pub const MAX_T_COST: u32 = 10;
/// The most lanes [`verify_password`] and [`hash_password`] agree to use.
pub const MAX_P_COST: u32 = 8;

/// Upper bounds on the Argon2id costs a call accepts, checked before anything is allocated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
    /// Largest memory cost, in KiB.
    pub max_m_cost: u32,
    /// Largest number of passes.
    pub max_t_cost: u32,
    /// Largest number of lanes.
    pub max_p_cost: u32,
}

impl Limits {
    /// The default limits: [`MAX_M_COST`] (256 MiB), [`MAX_T_COST`] (10) and [`MAX_P_COST`] (8).
    pub const DEFAULT: Self = Self {
        max_m_cost: MAX_M_COST,
        max_t_cost: MAX_T_COST,
        max_p_cost: MAX_P_COST,
    };

    fn allows(self, params: Params) -> bool {
        params.m_cost <= self.max_m_cost && params.t_cost <= self.max_t_cost && params.p_cost <= self.max_p_cost
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// Argon2id cost parameters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Params {
    /// Memory in KiB.
    pub m_cost: u32,
    /// Passes.
    pub t_cost: u32,
    /// Lanes.
    pub p_cost: u32,
}

impl Default for Params {
    fn default() -> Self {
        Self {
            m_cost: DEFAULT_M_COST,
            t_cost: DEFAULT_T_COST,
            p_cost: DEFAULT_P_COST,
        }
    }
}

impl Params {
    fn argon2(self, limits: Limits) -> Result<Argon2<'static>> {
        if !limits.allows(self) {
            return Err(Error::InvalidParams("Argon2 cost above the limits"));
        }
        let p = argon2::Params::new(self.m_cost, self.t_cost, self.p_cost, Some(32))
            .map_err(|_| Error::InvalidParams("Argon2 parameters out of range"))?;
        Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, p))
    }
}

/// Hashes `password` with a fresh random salt, returning a PHC string.
///
/// # Errors
/// [`Error::InvalidParams`] when the costs are out of range or above [`Limits::DEFAULT`] (so
/// every hash this function makes passes [`verify_password`]).
pub fn hash_password<R: Rng + ?Sized>(password: &[u8], params: Params, rng: &mut R) -> Result<String> {
    hash_password_with_limits(password, params, Limits::DEFAULT, rng)
}

/// [`hash_password`] with explicit cost limits, for hashes more expensive than the defaults
/// allow. Verify them with [`verify_password_with_limits`] and the same limits.
///
/// # Errors
/// [`Error::InvalidParams`] when the costs are out of range or above `limits`.
pub fn hash_password_with_limits<R: Rng + ?Sized>(
    password: &[u8],
    params: Params,
    limits: Limits,
    rng: &mut R,
) -> Result<String> {
    let salt: [u8; SALT_LEN] = crate::random(rng);
    let hash = params
        .argon2(limits)?
        .hash_password_with_salt(password, &salt)
        .map_err(|_| Error::InvalidParams("Argon2 hashing failed"))?;
    Ok(hash.to_string())
}

/// Checks `password` against an Argon2id PHC string (constant-time comparison inside `argon2`).
///
/// The costs in the string are checked against [`Limits::DEFAULT`] (256 MiB, 10 passes, 8
/// lanes) before any memory is allocated, so a hostile string cannot make a verification cost
/// gigabytes or minutes.
///
/// # Errors
/// [`Error::InvalidPasswordHash`] for a malformed string, another algorithm than Argon2id or
/// costs above the limits; [`Error::PasswordMismatch`] for a wrong password.
pub fn verify_password(password: &[u8], phc: &str) -> Result<()> {
    verify_password_with_limits(password, phc, Limits::DEFAULT)
}

/// [`verify_password`] with explicit cost limits: an opt-in for hashes made with costs above
/// [`Limits::DEFAULT`]. Raise the limits only for PHC strings from a trusted source.
///
/// # Errors
/// As [`verify_password`], with `limits` instead of the defaults.
pub fn verify_password_with_limits(password: &[u8], phc: &str, limits: Limits) -> Result<()> {
    let hash = PasswordHash::new(phc).map_err(|_| Error::InvalidPasswordHash)?;
    if hash.algorithm.as_str() != "argon2id" {
        return Err(Error::InvalidPasswordHash);
    }
    let params = argon2::Params::try_from(&hash).map_err(|_| Error::InvalidPasswordHash)?;
    Params {
        m_cost: params.m_cost(),
        t_cost: params.t_cost(),
        p_cost: params.p_cost(),
    }
    .argon2(limits)
    .map_err(|_| Error::InvalidPasswordHash)?;
    Argon2::default().verify_password(password, &hash).map_err(|e| match e {
        argon2::password_hash::Error::PasswordInvalid => Error::PasswordMismatch,
        _ => Error::InvalidPasswordHash,
    })
}

/// A fresh random salt of [`SALT_LEN`] (16) bytes for [`derive_key`].
#[must_use]
pub fn generate_salt<R: Rng + ?Sized>(rng: &mut R) -> [u8; SALT_LEN] {
    crate::random(rng)
}

/// A key derived by [`derive_key`]. Zeroized on drop; compared in constant time; `Debug` is
/// redacted.
#[derive(Clone)]
pub struct DerivedKey(Zeroizing<Vec<u8>>);

impl ZeroizeOnDrop for DerivedKey {}

impl DerivedKey {
    /// The key bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// The key length in bytes.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Always `false`: a derived key has at least [`MIN_KEY_LEN`] bytes.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl PartialEq for DerivedKey {
    fn eq(&self, other: &Self) -> bool {
        crate::ct_eq(&self.0, &other.0)
    }
}
impl Eq for DerivedKey {}

impl core::fmt::Debug for DerivedKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "DerivedKey(<redacted>, {} bytes)", self.0.len())
    }
}

/// Derives a `len`-byte key from `password` and `salt` with Argon2id: the same inputs always give
/// the same key (see the [module documentation](self) for the construction and its use).
///
/// # Errors
/// [`Error::InvalidParams`] for a salt shorter than [`MIN_SALT_LEN`], a length outside
/// [`MIN_KEY_LEN`]`..=`[`MAX_KEY_LEN`], or costs out of range or above [`Limits::DEFAULT`]
/// (checked before any memory is allocated).
pub fn derive_key(password: &[u8], salt: &[u8], params: Params, len: usize) -> Result<DerivedKey> {
    derive_key_with_limits(password, salt, params, Limits::DEFAULT, len)
}

/// [`derive_key`] with explicit cost limits: an opt-in for costs above [`Limits::DEFAULT`], for
/// example when they come from data written by a trusted source.
///
/// # Errors
/// As [`derive_key`], with `limits` instead of the defaults.
pub fn derive_key_with_limits(
    password: &[u8],
    salt: &[u8],
    params: Params,
    limits: Limits,
    len: usize,
) -> Result<DerivedKey> {
    argon2id(password, salt, b"", b"", params, limits, len)
}

/// Raw Argon2id with RFC 9106's optional secret `K` and associated data `X` (empty in
/// [`derive_key`]; set only by the RFC 9106 test vector).
fn argon2id(
    password: &[u8],
    salt: &[u8],
    secret: &[u8],
    data: &[u8],
    params: Params,
    limits: Limits,
    len: usize,
) -> Result<DerivedKey> {
    if salt.len() < MIN_SALT_LEN {
        return Err(Error::InvalidParams("Argon2 salt shorter than 16 bytes"));
    }
    if !(MIN_KEY_LEN..=MAX_KEY_LEN).contains(&len) {
        return Err(Error::InvalidParams("derived key length out of range"));
    }
    if !limits.allows(params) {
        return Err(Error::InvalidParams("Argon2 cost above the limits"));
    }
    let mut builder = argon2::ParamsBuilder::new();
    builder
        .m_cost(params.m_cost)
        .t_cost(params.t_cost)
        .p_cost(params.p_cost)
        .output_len(len);
    if !data.is_empty() {
        builder.data(argon2::AssociatedData::new(data).map_err(|_| Error::InvalidParams("Argon2 data too long"))?);
    }
    let p = builder
        .build()
        .map_err(|_| Error::InvalidParams("Argon2 parameters out of range"))?;
    let argon = if secret.is_empty() {
        Argon2::new(Algorithm::Argon2id, Version::V0x13, p)
    } else {
        Argon2::new_with_secret(secret, Algorithm::Argon2id, Version::V0x13, p)
            .map_err(|_| Error::InvalidParams("Argon2 secret too long"))?
    };
    let mut out = Zeroizing::new(vec![0u8; len]);
    argon
        .hash_password_into(password, salt, &mut out)
        .map_err(|_| Error::InvalidParams("Argon2 key derivation failed"))?;
    Ok(DerivedKey(out))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::rng;

    fn hex(s: &str) -> Vec<u8> {
        (0..s.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
            .collect()
    }

    /// RFC 9106, section 5.3: the Argon2id test vector (it sets a secret and associated data,
    /// which `derive_key` leaves empty, so it runs through the same internal function).
    #[test]
    fn rfc9106_argon2id_vector() {
        let params = Params {
            m_cost: 32,
            t_cost: 3,
            p_cost: 4,
        };
        let tag = argon2id(
            &[0x01; 32],
            &[0x02; 16],
            &[0x03; 8],
            &[0x04; 12],
            params,
            Limits::DEFAULT,
            32,
        )
        .unwrap();
        assert_eq!(
            tag.as_bytes(),
            hex("0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659")
        );
    }

    /// Known answers of `derive_key` (no secret, no associated data), cross-checked with an
    /// independent implementation: OpenSSL's Argon2id through Node's `crypto.argon2Sync`.
    #[test]
    fn derive_key_known_answers() {
        let salt: Vec<u8> = (0u8..16).collect();
        let fast = derive_key(b"correct horse battery staple", &salt, FAST, 32).unwrap();
        assert_eq!(fast.as_bytes(), hex(KAT_FAST));
        let default = derive_key(
            b"correct horse battery staple",
            &salt,
            Params::default(),
            DEFAULT_KEY_LEN,
        )
        .unwrap();
        assert_eq!(default.as_bytes(), hex(KAT_DEFAULT));
        let long = derive_key("pässwörd".as_bytes(), &[0xa5; 32], FAST, MAX_KEY_LEN).unwrap();
        assert_eq!(long.as_bytes(), hex(KAT_LONG));
    }

    const KAT_FAST: &str = "8b34e4a5888ab048e962c074a314d5454f4f25bd88abe8e3d021388672c1d1a4";
    const KAT_DEFAULT: &str = "0d1a3c6523c8f06e4e0af9c515aa5b5448cfebd6838f2d52c3d8b6ef8ddc3c2e";
    const KAT_LONG: &str = concat!(
        "914828cf539677b4fd45fd184695a148aa8df256471ad940ae873426074e91c8",
        "80ebdc5db5916dbcdc6f0d365eb21ee54acc19a3e53bc9ecfd60d6e80ff1c88b"
    );

    #[test]
    fn derive_key_is_deterministic_and_input_bound() {
        let mut rng = rng();
        let salt = generate_salt(&mut rng);
        let a = derive_key(b"pw", &salt, FAST, 32).unwrap();
        assert_eq!(a, derive_key(b"pw", &salt, FAST, 32).unwrap());
        assert_eq!(a.len(), 32);
        assert!(!a.is_empty());
        let other_salt = generate_salt(&mut rng);
        assert_ne!(salt, other_salt);
        assert_ne!(a, derive_key(b"pw", &other_salt, FAST, 32).unwrap());
        assert_ne!(a, derive_key(b"pW", &salt, FAST, 32).unwrap());
        assert_ne!(a, derive_key(b"pw", &salt, Params { t_cost: 2, ..FAST }, 32).unwrap());
        // The length is an Argon2 input: a shorter key is not a prefix of a longer one.
        let short = derive_key(b"pw", &salt, FAST, 16).unwrap();
        assert_ne!(short.as_bytes(), &a.as_bytes()[..16]);
    }

    #[test]
    fn derive_key_refuses_bad_inputs_before_any_work() {
        let salt = [0u8; MIN_SALT_LEN];
        let invalid = |r: Result<DerivedKey>| matches!(r, Err(Error::InvalidParams(_)));
        assert!(invalid(derive_key(b"pw", &salt[..MIN_SALT_LEN - 1], FAST, 32)));
        assert!(invalid(derive_key(b"pw", &[], FAST, 32)));
        assert!(invalid(derive_key(b"pw", &salt, FAST, MIN_KEY_LEN - 1)));
        assert!(invalid(derive_key(b"pw", &salt, FAST, MAX_KEY_LEN + 1)));
        assert!(invalid(derive_key(b"pw", &salt, FAST, 0)));
        assert!(invalid(derive_key(b"pw", &salt, Params { m_cost: 1, ..FAST }, 32)));
        assert!(invalid(derive_key(b"pw", &salt, Params { t_cost: 0, ..FAST }, 32)));
        for (m, t, p) in [
            (MAX_M_COST + 1, 1, 1),
            (1024, MAX_T_COST + 1, 1),
            (1024, 1, MAX_P_COST + 1),
            (u32::MAX, u32::MAX, u32::MAX),
        ] {
            let start = std::time::Instant::now();
            let params = Params {
                m_cost: m,
                t_cost: t,
                p_cost: p,
            };
            assert_eq!(
                derive_key(b"pw", &salt, params, 32),
                Err(Error::InvalidParams("Argon2 cost above the limits")),
                "m={m} t={t} p={p}"
            );
            assert!(start.elapsed() < std::time::Duration::from_millis(50));
        }
        // Higher costs need the explicit opt-in.
        let slow = Params {
            t_cost: MAX_T_COST + 1,
            ..FAST
        };
        let raised = Limits {
            max_t_cost: MAX_T_COST + 1,
            ..Limits::DEFAULT
        };
        assert!(invalid(derive_key(b"pw", &salt, slow, 32)));
        derive_key_with_limits(b"pw", &salt, slow, raised, 32).unwrap();
    }

    #[test]
    fn derived_key_debug_is_redacted() {
        fn assert_zod<T: ZeroizeOnDrop>() {}
        let key = derive_key(b"pw", &[7u8; 16], FAST, 32).unwrap();
        let dbg = format!("{key:?}");
        assert_eq!(dbg, "DerivedKey(<redacted>, 32 bytes)");
        assert_zod::<DerivedKey>();
    }

    const FAST: Params = Params {
        m_cost: 256,
        t_cost: 1,
        p_cost: 1,
    };

    #[test]
    fn round_trip() {
        let mut rng = rng();
        let phc = hash_password(b"correct horse", FAST, &mut rng).unwrap();
        assert!(phc.starts_with("$argon2id$v=19$m=256,t=1,p=1$"));
        verify_password(b"correct horse", &phc).unwrap();
        assert_eq!(verify_password(b"wrong", &phc), Err(Error::PasswordMismatch));
    }

    #[test]
    fn defaults() {
        assert_eq!(
            Params::default(),
            Params {
                m_cost: 65536,
                t_cost: 3,
                p_cost: 1
            }
        );
    }

    #[test]
    fn rejects_bad_strings() {
        assert_eq!(verify_password(b"x", "nope"), Err(Error::InvalidPasswordHash));
        // Argon2i is refused.
        assert_eq!(
            verify_password(
                b"x",
                "$argon2i$v=19$m=256,t=2,p=1$c29tZXNhbHQ$nf65EOgLrQMR/uIPnA4rEsF5h7TKyQwu9U1bMCHGi/4"
            ),
            Err(Error::InvalidPasswordHash)
        );
        // Memory cost above the cap is refused before any work.
        assert_eq!(
            verify_password(
                b"x",
                "$argon2id$v=19$m=4294967295,t=2,p=1$c29tZXNhbHQ$nf65EOgLrQMR/uIPnA4rEsF5h7TKyQwu9U1bMCHGi/4"
            ),
            Err(Error::InvalidPasswordHash)
        );
        let mut rng = rng();
        assert!(hash_password(b"x", Params { m_cost: 1, ..FAST }, &mut rng).is_err());
    }

    const SALT: &str = "c29tZXNhbHRzb21lc2FsdA";
    const HASH: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    fn phc(m: u32, t: u32, p: u32) -> String {
        format!("$argon2id$v=19$m={m},t={t},p={p}${SALT}${HASH}")
    }

    /// Regression: `m=4194304,t=64` (4 GiB, about two minutes of CPU per verification) used to
    /// be accepted. Every cost above the default limits is now refused before any work.
    #[test]
    fn verify_refuses_costs_above_the_default_limits() {
        for (m, t, p) in [
            (4_194_304, 64, 1),
            (4_194_304, 1, 1),
            (MAX_M_COST + 1, 1, 1),
            (1024, MAX_T_COST + 1, 1),
            (1024, 1, MAX_P_COST + 1),
            (u32::MAX, u32::MAX, 1),
        ] {
            let start = std::time::Instant::now();
            assert_eq!(
                verify_password(b"x", &phc(m, t, p)),
                Err(Error::InvalidPasswordHash),
                "m={m} t={t} p={p}"
            );
            assert!(
                start.elapsed() < std::time::Duration::from_millis(50),
                "m={m} t={t} p={p}"
            );
        }
        // Within the limits, the hash is checked (and does not match).
        assert_eq!(
            verify_password(b"x", &phc(1024, MAX_T_COST, MAX_P_COST)),
            Err(Error::PasswordMismatch)
        );
        assert_eq!(Limits::default(), Limits::DEFAULT);
        assert_eq!((MAX_M_COST, MAX_T_COST, MAX_P_COST), (262_144, 10, 8));
    }

    #[test]
    fn limits_can_be_lowered_and_raised_explicitly() {
        let mut rng = rng();
        let tight = Limits {
            max_m_cost: 256,
            max_t_cost: 1,
            max_p_cost: 1,
        };
        let phc_fast = hash_password_with_limits(b"pw", FAST, tight, &mut rng).unwrap();
        verify_password_with_limits(b"pw", &phc_fast, tight).unwrap();
        assert_eq!(
            verify_password_with_limits(b"pw", &phc(264, 1, 1), tight),
            Err(Error::InvalidPasswordHash)
        );

        // A hash above the defaults needs the opt-in on both sides.
        let slow = Params {
            t_cost: MAX_T_COST + 1,
            ..FAST
        };
        assert!(hash_password(b"pw", slow, &mut rng).is_err());
        let raised = Limits {
            max_t_cost: MAX_T_COST + 1,
            ..Limits::DEFAULT
        };
        let phc_slow = hash_password_with_limits(b"pw", slow, raised, &mut rng).unwrap();
        assert_eq!(verify_password(b"pw", &phc_slow), Err(Error::InvalidPasswordHash));
        verify_password_with_limits(b"pw", &phc_slow, raised).unwrap();
        assert_eq!(
            verify_password_with_limits(b"other", &phc_slow, raised),
            Err(Error::PasswordMismatch)
        );
    }
}