orion 0.17.14

Usable, easy and safe pure-Rust crypto
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// MIT License

// Copyright (c) 2018-2026 The orion Developers

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! # Parameters:
//! - `password`: Password.
//! - `salt`: Salt value.
//! - `iterations`: Iteration count.
//! - `dst_out`: Destination buffer for the derived key. The length of the
//!   derived key is implied by the length of `dst_out`.
//! - `expected`: The expected derived key.
//!
//! # Errors:
//! An error will be returned if:
//! - The length of `dst_out` is less than 1.
//! - The specified iteration count is less than 1.
//! - The hashed password does not match the expected when verifying.
//!
//! # Panics:
//! A panic will occur if:
//! - The length of `dst_out` is greater than (2^32 - 1) * SHA(256/384/512)_OUTSIZE.
//!
//! # Security:
//! - Use [`Password::generate()`] to randomly generate a password of the same length as
//! the underlying SHA2 hash functions blocksize.
//! - Salts should always be generated using a CSPRNG.
//!   [`secure_rand_bytes()`] can be used for this.
//! - The recommended length for a salt is 64 bytes.
//! - The iteration count should be set as high as feasible. Please check [OWASP] for
//! the recommended minimum amount (600000 at the time of writing).
//! - Please note that when verifying, a copy of the computed password hash is placed into
//! `dst_out`. If the derived hash is considered sensitive and you want to provide defense
//! in depth against an attacker reading your application's private memory, then you as
//! the user are responsible for zeroing out this buffer (see the [`zeroize` crate]).
//!
//! # Example:
//! ```rust
//! # #[cfg(feature = "safe_api")] {
//! use orion::{hazardous::kdf::pbkdf2, util};
//!
//! let mut salt = [0u8; 64];
//! util::secure_rand_bytes(&mut salt)?;
//! let password = pbkdf2::sha512::Password::from_slice("Secret password".as_bytes())?;
//! let mut dst_out = [0u8; 64];
//!
//! pbkdf2::sha512::derive_key(&password, &salt, 10000, &mut dst_out)?;
//!
//! let expected_dk = dst_out;
//!
//! assert!(pbkdf2::sha512::verify(&expected_dk, &password, &salt, 10000, &mut dst_out).is_ok());
//! # }
//! # Ok::<(), orion::errors::UnknownCryptoError>(())
//! ```
//! [`Password::generate()`]: pbkdf2::sha512::Password::generate
//! [`secure_rand_bytes()`]: crate::util::secure_rand_bytes
//! [`zeroize` crate]: https://crates.io/crates/zeroize
//! [OWASP]: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html

use crate::{errors::UnknownCryptoError, hazardous::mac::hmac};

/// The F function as described in the RFC.
fn _function_f<Hmac>(
    salt: &[u8],
    iterations: usize,
    index: u32,
    dk_block: &mut [u8],
    block_len: usize,
    u_step: &mut [u8],
    hmac: &mut Hmac,
) -> Result<(), UnknownCryptoError>
where
    Hmac: hmac::HmacFunction,
{
    debug_assert_eq!(u_step.len(), Hmac::HASH_FUNC_OUTSIZE);
    hmac._update(salt)?;
    hmac._update(&index.to_be_bytes())?;
    hmac._finalize(u_step)?;
    debug_assert!(block_len <= u_step.len());
    dk_block.copy_from_slice(&u_step[..block_len]);

    if iterations > 1 {
        for _ in 1..iterations {
            hmac._reset();
            hmac._update(u_step)?;
            hmac._finalize(u_step)?;
            xor_slices!(u_step, dk_block);
        }
    }

    Ok(())
}

///
///
/// NOTE: Hmac has the output size of the hash function defined,
/// but the array initialization with the size cannot depend on a generic parameter,
/// because we don't have full support for const generics yet.
fn _derive_key<Hmac, const OUTSIZE: usize>(
    padded_password: &[u8],
    salt: &[u8],
    iterations: usize,
    dest: &mut [u8],
) -> Result<(), UnknownCryptoError>
where
    Hmac: hmac::HmacFunction,
{
    debug_assert_eq!(OUTSIZE, Hmac::HASH_FUNC_OUTSIZE);
    if dest.is_empty() || iterations < 1 {
        return Err(UnknownCryptoError);
    }

    let mut u_step = [0u8; OUTSIZE];
    let mut hmac = Hmac::_new(padded_password)?;
    for (idx, dk_block) in dest.chunks_mut(Hmac::HASH_FUNC_OUTSIZE).enumerate() {
        // If this panics, then the size limit for PBKDF2 is reached.
        let block_idx: u32 = 1u32.checked_add(idx as u32).unwrap();

        _function_f(
            salt,
            iterations,
            block_idx,
            dk_block,
            dk_block.len(),
            &mut u_step,
            &mut hmac,
        )?;

        hmac._reset();
    }

    Ok(())
}

///
///
/// NOTE: Hmac has the output size of the hash function defined,
/// but the array initialization with the size cannot depend on a generic parameter,
/// because we don't have full support for const generics yet.
fn _verify<Hmac, const OUTSIZE: usize>(
    expected: &[u8],
    padded_password: &[u8],
    salt: &[u8],
    iterations: usize,
    dest: &mut [u8],
) -> Result<(), UnknownCryptoError>
where
    Hmac: hmac::HmacFunction,
{
    debug_assert_eq!(OUTSIZE, Hmac::HASH_FUNC_OUTSIZE);
    _derive_key::<Hmac, { OUTSIZE }>(padded_password, salt, iterations, dest)?;
    crate::util::secure_cmp(expected, dest)
}

/// PBKDF2-HMAC-SHA256 (Password-Based Key Derivation Function 2) as specified in the [RFC 8018](https://tools.ietf.org/html/rfc8018).
pub mod sha256 {
    use super::*;
    use crate::hazardous::hash::sha2::sha256::{self, Sha256};

    construct_hmac_key! {
        /// A type to represent the `Password` that PBKDF2 hashes.
        ///
        /// # Note:
        /// Because `Password` is used as a `SecretKey` for HMAC during hashing, `Password` already
        /// pads the given password to a length of 64, for use in HMAC, when initialized.
        ///
        /// Using `unprotected_as_bytes()` will return the password with padding.
        ///
        /// Using `get_length()` will return the length with padding (always 64).
        ///
        /// # Panics:
        /// A panic will occur if:
        /// - Failure to generate random bytes securely.
        (Password, Sha256, sha256::SHA256_OUTSIZE, test_pbkdf2_password, sha256::SHA256_BLOCKSIZE)
    }

    #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."]
    /// Derive a key using PBKDF2-HMAC-SHA256.
    pub fn derive_key(
        password: &Password,
        salt: &[u8],
        iterations: usize,
        dst_out: &mut [u8],
    ) -> Result<(), UnknownCryptoError> {
        _derive_key::<hmac::sha256::HmacSha256, { sha256::SHA256_OUTSIZE }>(
            password.unprotected_as_bytes(),
            salt,
            iterations,
            dst_out,
        )
    }

    #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."]
    /// Verify PBKDF2-HMAC-SHA256 derived key in constant time.
    pub fn verify(
        expected: &[u8],
        password: &Password,
        salt: &[u8],
        iterations: usize,
        dst_out: &mut [u8],
    ) -> Result<(), UnknownCryptoError> {
        _verify::<hmac::sha256::HmacSha256, { sha256::SHA256_OUTSIZE }>(
            expected,
            password.unprotected_as_bytes(),
            salt,
            iterations,
            dst_out,
        )
    }
}

/// PBKDF2-HMAC-SHA384 (Password-Based Key Derivation Function 2) as specified in the [RFC 8018](https://tools.ietf.org/html/rfc8018).
pub mod sha384 {
    use super::*;
    use crate::hazardous::hash::sha2::sha384::{self, Sha384};

    construct_hmac_key! {
        /// A type to represent the `Password` that PBKDF2 hashes.
        ///
        /// # Note:
        /// Because `Password` is used as a `SecretKey` for HMAC during hashing, `Password` already
        /// pads the given password to a length of 128, for use in HMAC, when initialized.
        ///
        /// Using `unprotected_as_bytes()` will return the password with padding.
        ///
        /// Using `get_length()` will return the length with padding (always 128).
        ///
        /// # Panics:
        /// A panic will occur if:
        /// - Failure to generate random bytes securely.
        (Password, Sha384, sha384::SHA384_OUTSIZE, test_pbkdf2_password, sha384::SHA384_BLOCKSIZE)
    }

    #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."]
    /// Derive a key using PBKDF2-HMAC-SHA384.
    pub fn derive_key(
        password: &Password,
        salt: &[u8],
        iterations: usize,
        dst_out: &mut [u8],
    ) -> Result<(), UnknownCryptoError> {
        _derive_key::<hmac::sha384::HmacSha384, { sha384::SHA384_OUTSIZE }>(
            password.unprotected_as_bytes(),
            salt,
            iterations,
            dst_out,
        )
    }

    #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."]
    /// Verify PBKDF2-HMAC-SHA384 derived key in constant time.
    pub fn verify(
        expected: &[u8],
        password: &Password,
        salt: &[u8],
        iterations: usize,
        dst_out: &mut [u8],
    ) -> Result<(), UnknownCryptoError> {
        _verify::<hmac::sha384::HmacSha384, { sha384::SHA384_OUTSIZE }>(
            expected,
            password.unprotected_as_bytes(),
            salt,
            iterations,
            dst_out,
        )
    }
}

/// PBKDF2-HMAC-SHA512 (Password-Based Key Derivation Function 2) as specified in the [RFC 8018](https://tools.ietf.org/html/rfc8018).
pub mod sha512 {
    use super::*;
    use crate::hazardous::hash::sha2::sha512::{self, Sha512};

    construct_hmac_key! {
        /// A type to represent the `Password` that PBKDF2 hashes.
        ///
        /// # Note:
        /// Because `Password` is used as a `SecretKey` for HMAC during hashing, `Password` already
        /// pads the given password to a length of 128, for use in HMAC, when initialized.
        ///
        /// Using `unprotected_as_bytes()` will return the password with padding.
        ///
        /// Using `get_length()` will return the length with padding (always 128).
        ///
        /// # Panics:
        /// A panic will occur if:
        /// - Failure to generate random bytes securely.
        (Password, Sha512, sha512::SHA512_OUTSIZE, test_pbkdf2_password, sha512::SHA512_BLOCKSIZE)
    }

    #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."]
    /// Derive a key using PBKDF2-HMAC-SHA512.
    pub fn derive_key(
        password: &Password,
        salt: &[u8],
        iterations: usize,
        dst_out: &mut [u8],
    ) -> Result<(), UnknownCryptoError> {
        _derive_key::<hmac::sha512::HmacSha512, { sha512::SHA512_OUTSIZE }>(
            password.unprotected_as_bytes(),
            salt,
            iterations,
            dst_out,
        )
    }

    #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."]
    /// Verify PBKDF2-HMAC-SHA512 derived key in constant time.
    pub fn verify(
        expected: &[u8],
        password: &Password,
        salt: &[u8],
        iterations: usize,
        dst_out: &mut [u8],
    ) -> Result<(), UnknownCryptoError> {
        _verify::<hmac::sha512::HmacSha512, { sha512::SHA512_OUTSIZE }>(
            expected,
            password.unprotected_as_bytes(),
            salt,
            iterations,
            dst_out,
        )
    }
}

// Testing public functions in the module.
#[cfg(test)]
mod public {
    use super::*;

    mod test_verify {
        use super::*;

        #[test]
        fn verify_true() {
            let password_256 = sha256::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_384 = sha384::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_512 = sha512::Password::from_slice("pass\0word".as_bytes()).unwrap();

            let salt = "sa\0lt".as_bytes();
            let iterations: usize = 128;
            let mut okm_out = [0u8; 16];
            let mut okm_out_verify = [0u8; 16];

            sha256::derive_key(&password_256, salt, iterations, &mut okm_out).unwrap();
            assert!(sha256::verify(
                &okm_out,
                &password_256,
                salt,
                iterations,
                &mut okm_out_verify
            )
            .is_ok());

            sha384::derive_key(&password_384, salt, iterations, &mut okm_out).unwrap();
            assert!(sha384::verify(
                &okm_out,
                &password_384,
                salt,
                iterations,
                &mut okm_out_verify
            )
            .is_ok());

            sha512::derive_key(&password_512, salt, iterations, &mut okm_out).unwrap();
            assert!(sha512::verify(
                &okm_out,
                &password_512,
                salt,
                iterations,
                &mut okm_out_verify
            )
            .is_ok());
        }

        #[test]
        fn verify_false_wrong_salt() {
            let password_256 = sha256::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_384 = sha384::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_512 = sha512::Password::from_slice("pass\0word".as_bytes()).unwrap();

            let salt = "sa\0lt".as_bytes();
            let iterations: usize = 128;
            let mut okm_out = [0u8; 16];
            let mut okm_out_verify = [0u8; 16];

            sha256::derive_key(&password_256, salt, iterations, &mut okm_out).unwrap();
            assert!(sha256::verify(
                &okm_out,
                &password_256,
                b"",
                iterations,
                &mut okm_out_verify
            )
            .is_err());

            sha384::derive_key(&password_384, salt, iterations, &mut okm_out).unwrap();
            assert!(sha384::verify(
                &okm_out,
                &password_384,
                b"",
                iterations,
                &mut okm_out_verify
            )
            .is_err());

            sha512::derive_key(&password_512, salt, iterations, &mut okm_out).unwrap();
            assert!(sha512::verify(
                &okm_out,
                &password_512,
                b"",
                iterations,
                &mut okm_out_verify
            )
            .is_err());
        }
        #[test]
        fn verify_false_wrong_password() {
            let password_256 = sha256::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_384 = sha384::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_512 = sha512::Password::from_slice("pass\0word".as_bytes()).unwrap();

            let salt = "sa\0lt".as_bytes();
            let iterations: usize = 128;
            let mut okm_out = [0u8; 16];
            let mut okm_out_verify = [0u8; 16];

            sha256::derive_key(&password_256, salt, iterations, &mut okm_out).unwrap();
            assert!(sha256::verify(
                &okm_out,
                &sha256::Password::from_slice(b"pass").unwrap(),
                salt,
                iterations,
                &mut okm_out_verify
            )
            .is_err());

            sha384::derive_key(&password_384, salt, iterations, &mut okm_out).unwrap();
            assert!(sha384::verify(
                &okm_out,
                &sha384::Password::from_slice(b"pass").unwrap(),
                salt,
                iterations,
                &mut okm_out_verify
            )
            .is_err());

            sha512::derive_key(&password_512, salt, iterations, &mut okm_out).unwrap();
            assert!(sha512::verify(
                &okm_out,
                &sha512::Password::from_slice(b"pass").unwrap(),
                salt,
                iterations,
                &mut okm_out_verify
            )
            .is_err());
        }

        #[test]
        fn verify_diff_dklen_error() {
            let password_256 = sha256::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_384 = sha384::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_512 = sha512::Password::from_slice("pass\0word".as_bytes()).unwrap();

            let salt = "sa\0lt".as_bytes();
            let iterations: usize = 128;
            let mut okm_out = [0u8; 16];
            let mut okm_out_verify = [0u8; 32];

            sha256::derive_key(&password_256, salt, iterations, &mut okm_out).unwrap();
            assert!(sha256::verify(
                &okm_out,
                &password_256,
                salt,
                iterations,
                &mut okm_out_verify
            )
            .is_err());

            sha384::derive_key(&password_384, salt, iterations, &mut okm_out).unwrap();
            assert!(sha384::verify(
                &okm_out,
                &password_384,
                salt,
                iterations,
                &mut okm_out_verify
            )
            .is_err());

            sha512::derive_key(&password_512, salt, iterations, &mut okm_out).unwrap();
            assert!(sha512::verify(
                &okm_out,
                &password_512,
                salt,
                iterations,
                &mut okm_out_verify
            )
            .is_err());
        }

        #[test]
        fn verify_diff_iter_error() {
            let password_256 = sha256::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_384 = sha384::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_512 = sha512::Password::from_slice("pass\0word".as_bytes()).unwrap();

            let salt = "sa\0lt".as_bytes();
            let iterations: usize = 128;
            let mut okm_out = [0u8; 16];
            let mut okm_out_verify = [0u8; 16];

            sha256::derive_key(&password_256, salt, iterations, &mut okm_out).unwrap();
            assert!(
                sha256::verify(&okm_out, &password_256, salt, 127, &mut okm_out_verify).is_err()
            );

            sha384::derive_key(&password_384, salt, iterations, &mut okm_out).unwrap();
            assert!(
                sha384::verify(&okm_out, &password_384, salt, 127, &mut okm_out_verify).is_err()
            );

            sha512::derive_key(&password_512, salt, iterations, &mut okm_out).unwrap();
            assert!(
                sha512::verify(&okm_out, &password_512, salt, 127, &mut okm_out_verify).is_err()
            );
        }
    }

    mod test_derive_key {
        use super::*;

        #[test]
        fn zero_iterations_err() {
            let password_256 = sha256::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_384 = sha384::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_512 = sha512::Password::from_slice("pass\0word".as_bytes()).unwrap();

            let salt = "salt".as_bytes();
            let iterations: usize = 0;
            let mut okm_out = [0u8; 15];

            assert!(sha256::derive_key(&password_256, salt, iterations, &mut okm_out).is_err());
            assert!(sha384::derive_key(&password_384, salt, iterations, &mut okm_out).is_err());
            assert!(sha512::derive_key(&password_512, salt, iterations, &mut okm_out).is_err());
        }

        #[test]
        fn zero_dklen_err() {
            let password_256 = sha256::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_384 = sha384::Password::from_slice("pass\0word".as_bytes()).unwrap();
            let password_512 = sha512::Password::from_slice("pass\0word".as_bytes()).unwrap();

            let salt = "salt".as_bytes();
            let iterations: usize = 1;
            let mut okm_out = [0u8; 0];

            assert!(sha256::derive_key(&password_256, salt, iterations, &mut okm_out).is_err());
            assert!(sha384::derive_key(&password_384, salt, iterations, &mut okm_out).is_err());
            assert!(sha512::derive_key(&password_512, salt, iterations, &mut okm_out).is_err());
        }
    }
}