Created
February 23, 2024 05:12
-
-
Save DefectingCat/749e1d291133198a995f252a8d610628 to your computer and use it in GitHub Desktop.
rust argon2 password hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use anyhow::{anyhow, Context}; | |
use tokio::task; | |
use argon2::password_hash::SaltString; | |
use argon2::{password_hash, Argon2, PasswordHash, PasswordHasher, PasswordVerifier}; | |
pub async fn hash(password: String) -> anyhow::Result<String> { | |
task::spawn_blocking(move || { | |
let salt = SaltString::generate(rand::thread_rng()); | |
Ok(Argon2::default() | |
.hash_password(password.as_bytes(), &salt) | |
.map_err(|e| anyhow!(e).context("failed to hash password"))? | |
.to_string()) | |
}) | |
.await | |
.context("panic in hash()")? | |
} | |
pub async fn verify(password: String, hash: String) -> anyhow::Result<bool> { | |
task::spawn_blocking(move || { | |
let hash = PasswordHash::new(&hash) | |
.map_err(|e| anyhow!(e).context("BUG: password hash invalid"))?; | |
let res = Argon2::default().verify_password(password.as_bytes(), &hash); | |
match res { | |
Ok(()) => Ok(true), | |
Err(password_hash::Error::Password) => Ok(false), | |
Err(e) => Err(anyhow!(e).context("failed to verify password")), | |
} | |
}) | |
.await | |
.context("panic in verify()")? | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment