Skip to main content

utopia_auth/
firebase.rs

1//! Firebase's modified scrypt, as `Utopia\Auth\Hashes\ScryptModified` computes it: scrypt
2//! (N = 16384, r = 8, p = 1, 64 bytes) of the password under the salt and its separator, and
3//! the signer key encrypted with AES-256-CTR under the first 32 bytes of that, from a zero IV.
4
5use aes::Aes256;
6use aes::cipher::{BlockEncrypt, KeyInit};
7use zeroize::Zeroize;
8
9use crate::scrypt::{Failure, scrypt};
10
11/// `scrypt($password, $salt . $separator, 16384, 8, 1, 64)`, raw: `ScryptModified`'s
12/// derived key. The password is what PHP passes, already through `mb_convert_encoding()`.
13///
14/// # Errors
15///
16/// [`Failure::False`] when scrypt's 16 MiB cannot be allocated.
17pub fn derived_key(password: &[u8], salt: &[u8], separator: &[u8]) -> Result<Vec<u8>, Failure> {
18    let mut joined = Vec::with_capacity(salt.len() + separator.len());
19    joined.extend_from_slice(salt);
20    joined.extend_from_slice(separator);
21    scrypt(password, &joined, 16384, 8, 1, 64)
22}
23
24/// `openssl_encrypt($data, 'aes-256-ctr', $key, OPENSSL_RAW_DATA, str_repeat("\0", 16))`:
25/// `data` XORed with the AES-256 keystream of a big-endian 128-bit counter from zero.
26#[must_use]
27pub fn aes_256_ctr(key: &[u8; 32], data: &[u8]) -> Vec<u8> {
28    let cipher = Aes256::new(key.into());
29    let mut out = Vec::with_capacity(data.len());
30    for (counter, chunk) in data.chunks(16).enumerate() {
31        let mut block = (counter as u128).to_be_bytes().into();
32        cipher.encrypt_block(&mut block);
33        out.extend(chunk.iter().zip(block.iter()).map(|(d, k)| d ^ k));
34        block.zeroize();
35    }
36    out
37}
38
39/// `ScryptModified::hash()`'s value before its `base64_encode()`: the signer key encrypted
40/// under the derived key's first 32 bytes.
41///
42/// # Errors
43///
44/// As [`derived_key`].
45pub fn hash(password: &[u8], salt: &[u8], separator: &[u8], signer_key: &[u8]) -> Result<Vec<u8>, Failure> {
46    let mut derived = derived_key(password, salt, separator)?;
47    let mut key = [0u8; 32];
48    key.copy_from_slice(&derived[..32]);
49    let encrypted = aes_256_ctr(&key, signer_key);
50    key.zeroize();
51    derived.zeroize();
52    Ok(encrypted)
53}
54
55#[cfg(test)]
56mod tests {
57    use super::{aes_256_ctr, hash};
58
59    fn b64(s: &str) -> Vec<u8> {
60        php_std::encoding::base64_decode(s.as_bytes(), true).unwrap()
61    }
62
63    /// Firebase's published test vector for its scrypt variant
64    /// (github.com/firebase/scrypt, `README.md`).
65    #[test]
66    fn firebase_vector() {
67        let signer = b64("jxspr8Ki0RYycVU8zykbdLGjFQ3McFUH0uiiTvC8pVMXAn210wjLNmdZJzxUECKbm0QsEmYUSDzZvpjeJ9WmXA==");
68        let separator = b64("Bw==");
69        let salt = b64("42xEC+ixf3L2lw==");
70        let hashed = hash(b"user1password", &salt, &separator, &signer).unwrap();
71        assert_eq!(
72            php_std::encoding::base64_encode(&hashed),
73            "lSrfV15cpx95/sZS2W9c9Kp6i/LVgQNDNC/qzrCnh1SAyZvqmZqAjTdn3aoItz+VHjoZilo78198JAdRuid5lQ=="
74        );
75    }
76
77    /// Empty input, a partial block, and CTR's symmetry.
78    #[test]
79    fn empty_and_partial_blocks() {
80        assert!(aes_256_ctr(&[0u8; 32], b"").is_empty());
81        assert_eq!(aes_256_ctr(&[7u8; 32], b"abc").len(), 3);
82        // XOR twice returns the input.
83        let once = aes_256_ctr(&[7u8; 32], b"0123456789abcdefXYZ");
84        assert_eq!(aes_256_ctr(&[7u8; 32], &once), b"0123456789abcdefXYZ");
85    }
86}