#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RandomError;
impl RandomError {
pub const MESSAGE: &'static str = "Could not gather sufficient random data";
}
impl std::fmt::Display for RandomError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(Self::MESSAGE)
}
}
impl std::error::Error for RandomError {}
pub fn random_bytes(length: usize) -> Result<Vec<u8>, RandomError> {
let mut bytes = vec![0u8; length];
getrandom::fill(&mut bytes).map_err(|_| RandomError)?;
Ok(bytes)
}
pub fn password_salt(length: usize) -> Result<Vec<u8>, RandomError> {
let encoded = php_std::encoding::base64_encode(&random_bytes(length * 3 / 4 + 1)?);
Ok(encoded.bytes().take(length).map(|b| if b == b'+' { b'.' } else { b }).collect())
}
#[cfg(test)]
mod tests {
#[test]
fn password_salts_are_php_salts() {
for length in [16, 22] {
let salt = super::password_salt(length).unwrap();
assert_eq!(salt.len(), length);
assert!(salt.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'.' || *b == b'/'));
}
}
}