//! Password hashing with argon2id. Used for account passwords and for share-link passwords. The //! blocking versions are slow by design, so async callers use the `_async` functions, which run them //! on tokio's blocking pool. use argon2::password_hash::phc::PasswordHash; use argon2::password_hash::{PasswordHasher, PasswordVerifier}; use argon2::{Algorithm, Argon2, Params, Version}; use crate::error::{Error, Result}; /// Memory cost of a hash, in KiB (19 MiB), time cost and lanes. They are written out here, not left to the /// crate's defaults, so a crate upgrade cannot change new hashes silently. A stored hash carries its own /// parameters, so every hash made before still verifies. const M_COST_KIB: u32 = 19 * 1024; const T_COST: u32 = 2; const P_COST: u32 = 1; /// The argon2id hasher with the pinned parameters. fn hasher() -> Argon2<'static> { let params = Params::new(M_COST_KIB, T_COST, P_COST, None) .expect("the pinned argon2 parameters are valid"); Argon2::new(Algorithm::Argon2id, Version::V0x13, params) } /// Hashes `pw` with argon2id (pinned parameters) and a random salt. Returns a PHC string. pub fn hash_password(pw: &str) -> Result { // The trait method draws a fresh salt from the OS RNG. hasher() .hash_password(pw.as_bytes()) .map(|h| h.to_string()) .map_err(|e| Error::Crypto(format!("argon2: {e}"))) } /// Returns true only if `pw` matches the PHC string `hash`. A malformed hash also gives false, so /// callers never have to tell "bad hash" apart from "wrong password". pub fn verify_password(pw: &str, hash: &str) -> bool { let Ok(parsed) = PasswordHash::new(hash) else { return false; }; hasher().verify_password(pw.as_bytes(), &parsed).is_ok() } /// [`hash_password`] on the blocking pool, so the async runtime is not held for the hashing time. pub async fn hash_password_async(pw: String) -> Result { tokio::task::spawn_blocking(move || hash_password(&pw)) .await .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))? } /// [`verify_password`] on the blocking pool. pub async fn verify_password_async(pw: String, hash: String) -> Result { tokio::task::spawn_blocking(move || verify_password(&pw, &hash)) .await .map_err(|e| Error::Crypto(format!("verify task failed: {e}"))) }