use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
use argon2::password_hash::SaltString;
use anyhow::{Context, Result};
/// Hash a password using Argon2
pub fn hash_password(password: &str) -> Result<String> {
// Use a simple salt for now - in production you'd want proper random salt generation
let salt = SaltString::encode_b64(&[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]).map_err(|e| anyhow::anyhow!("Failed to generate salt: {}", e))?;
let argon2 = Argon2::default();
let password_hash = argon2
.hash_password(password.as_bytes(), &salt)
.context("Failed to hash password")?;
Ok(password_hash.to_string())
}
/// Verify a password against its hash
pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
let parsed_hash = PasswordHash::new(hash).context("Failed to parse password hash")?;
let argon2 = Argon2::default();
match argon2.verify_password(password.as_bytes(), &parsed_hash) {
Ok(()) => Ok(true),
Err(argon2::password_hash::Error::Password) => Ok(false),
Err(e) => Err(anyhow::anyhow!("Password verification error: {}", e)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_password_hashing() {
let password = "test_password_123";
let hash = hash_password(password).expect("Failed to hash password");
// Verify correct password
assert!(verify_password(password, &hash).unwrap());
// Verify incorrect password
assert!(!verify_password("wrong_password", &hash).unwrap());
}
}
⭐
Log in to mark this repository.
1.6 KiB · text
History
1ce9641