forge
Explore
Log in

Don't you dare go Hollow

in

Clone
★ 0

0 watching0 forksRustAGPL-3.0528.7 KiB9215377Tahinli27 days ago37 commits

password.rs55 lines, 2.3 KiBHistoryRawDownload
1//! Password hashing with argon2id. Used for account passwords and for share-link passwords. The
2//! blocking versions are slow by design, so async callers use the `_async` functions, which run them
3//! on tokio's blocking pool.
4
5use argon2::password_hash::phc::PasswordHash;
6use argon2::password_hash::{PasswordHasher, PasswordVerifier};
7use argon2::{Algorithm, Argon2, Params, Version};
8
9use crate::error::{Error, Result};
10
11/// Memory cost of a hash, in KiB (19 MiB), time cost and lanes. They are written out here, not left to the
12/// crate's defaults, so a crate upgrade cannot change new hashes silently. A stored hash carries its own
13/// parameters, so every hash made before still verifies.
14const M_COST_KIB: u32 = 19 * 1024;
15const T_COST: u32 = 2;
16const P_COST: u32 = 1;
17
18/// The argon2id hasher with the pinned parameters.
19fn hasher() -> Argon2<'static> {
20 let params = Params::new(M_COST_KIB, T_COST, P_COST, None)
21 .expect("the pinned argon2 parameters are valid");
22 Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
23}
24
25/// Hashes `pw` with argon2id (pinned parameters) and a random salt. Returns a PHC string.
26pub fn hash_password(pw: &str) -> Result<String> {
27 // The trait method draws a fresh salt from the OS RNG.
28 hasher()
29 .hash_password(pw.as_bytes())
30 .map(|h| h.to_string())
31 .map_err(|e| Error::Crypto(format!("argon2: {e}")))
32}
33
34/// Returns true only if `pw` matches the PHC string `hash`. A malformed hash also gives false, so
35/// callers never have to tell "bad hash" apart from "wrong password".
36pub fn verify_password(pw: &str, hash: &str) -> bool {
37 let Ok(parsed) = PasswordHash::new(hash) else {
38 return false;
39 };
40 hasher().verify_password(pw.as_bytes(), &parsed).is_ok()
41}
42
43/// [`hash_password`] on the blocking pool, so the async runtime is not held for the hashing time.
44pub async fn hash_password_async(pw: String) -> Result<String> {
45 tokio::task::spawn_blocking(move || hash_password(&pw))
46 .await
47 .map_err(|e| Error::Crypto(format!("hashing task failed: {e}")))?
48}
49
50/// [`verify_password`] on the blocking pool.
51pub async fn verify_password_async(pw: String, hash: String) -> Result<bool> {
52 tokio::task::spawn_blocking(move || verify_password(&pw, &hash))
53 .await
54 .map_err(|e| Error::Crypto(format!("verify task failed: {e}")))
55}