Skip to main content

utopia_auth/
lib.rs

1//! The password hash algorithms of `utopia-php/auth` (`Utopia\Auth\Hashes`) that PHP
2//! itself does not provide: the scrypt KDF of the PECL `scrypt` extension, Firebase's
3//! modified scrypt, and phpass's portable hashes. The rest (`password_hash()`,
4//! `password_verify()`, `crypt()`, `hash()`) are PHP's own functions, ported in `php-std`.
5//!
6//! Every function here returns what PHP returns for the same input, byte for byte, including
7//! where PHP fails: [`scrypt::scrypt`] fails as `scrypt()` does, with its `Error`s, its
8//! warnings and its `false`.
9
10pub mod firebase;
11pub mod phpass;
12pub mod scrypt;
13
14/// PHP `random_bytes($length)`: bytes from the operating system's CSPRNG.
15///
16/// # Panics
17///
18/// When the operating system cannot provide random bytes, where PHP throws its `Exception`
19/// ("Could not gather sufficient random data").
20#[must_use]
21pub fn random_bytes(length: usize) -> Vec<u8> {
22    let mut bytes = vec![0u8; length];
23    getrandom::fill(&mut bytes).expect("the operating system provides random bytes");
24    bytes
25}
26
27/// `php_password_make_salt($length)`, the salt `password_hash()` draws: `$length * 3 / 4 + 1`
28/// random bytes in base64, `+` as `.`, cut to `$length` characters (22 for bcrypt, 16 for
29/// Argon2, which hashes these characters as its salt).
30#[must_use]
31pub fn password_salt(length: usize) -> Vec<u8> {
32    let encoded = php_std::encoding::base64_encode(&random_bytes(length * 3 / 4 + 1));
33    encoded.bytes().take(length).map(|b| if b == b'+' { b'.' } else { b }).collect()
34}
35
36/// PHP `hash_equals($known, $user)`: false at once when the lengths differ (PHP leaks the
37/// length too), otherwise a comparison whose time does not depend on where they differ.
38#[must_use]
39pub fn hash_equals(known: &[u8], user: &[u8]) -> bool {
40    if known.len() != user.len() {
41        return false;
42    }
43    let difference = known.iter().zip(user).fold(0u8, |acc, (a, b)| acc | (a ^ b));
44    // `black_box` keeps the compiler from turning the fold into an early-exit comparison.
45    std::hint::black_box(difference) == 0
46}
47
48#[cfg(test)]
49mod tests {
50    use super::hash_equals;
51
52    #[test]
53    fn password_salts_are_php_salts() {
54        for length in [16, 22] {
55            let salt = super::password_salt(length);
56            assert_eq!(salt.len(), length);
57            assert!(salt.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'.' || *b == b'/'));
58        }
59    }
60
61    #[test]
62    fn hash_equals_is_php_hash_equals() {
63        assert!(hash_equals(b"", b""));
64        assert!(hash_equals(b"abc", b"abc"));
65        assert!(!hash_equals(b"abc", b"abd"));
66        assert!(!hash_equals(b"abc", b"ab"));
67        assert!(!hash_equals(b"ab", b"abc"));
68    }
69}