Skip to content

Instantly share code, notes, and snippets.

@DefectingCat
Created February 23, 2024 05:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DefectingCat/749e1d291133198a995f252a8d610628 to your computer and use it in GitHub Desktop.
Save DefectingCat/749e1d291133198a995f252a8d610628 to your computer and use it in GitHub Desktop.
rust argon2 password hash
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