serenade_security/
password.rs1use argon2::Argon2;
4use argon2::password_hash::{
5 PasswordHasher as _, PasswordVerifier,
6 phc::{PasswordHash, SaltString},
7};
8
9use crate::SecurityError;
10
11pub trait PasswordHasher: Send + Sync {
13 fn hash(&self, plain: &str) -> Result<String, SecurityError>;
19
20 fn verify(&self, hashed: &str, plain: &str) -> Result<bool, SecurityError>;
26}
27
28#[derive(Clone, Copy, Debug, Default)]
30pub struct Argon2idPasswordHasher;
31
32impl Argon2idPasswordHasher {
33 #[must_use]
35 pub const fn new() -> Self {
36 Self
37 }
38}
39
40impl PasswordHasher for Argon2idPasswordHasher {
41 fn hash(&self, plain: &str) -> Result<String, SecurityError> {
42 if plain.is_empty() {
43 return Err(SecurityError::Password {
44 message: String::from("password must not be empty"),
45 });
46 }
47 Ok(hash_password_with_salt(plain, &random_salt()))
48 }
49
50 fn verify(&self, hashed: &str, plain: &str) -> Result<bool, SecurityError> {
51 let parsed = PasswordHash::new(hashed).map_err(|error| SecurityError::Password {
52 message: error.to_string(),
53 })?;
54 Ok(Argon2::default()
55 .verify_password(plain.as_bytes(), &parsed)
56 .is_ok())
57 }
58}
59
60fn random_salt() -> SaltString {
61 SaltString::generate()
62}
63
64fn hash_password_with_salt(plain: &str, salt: &SaltString) -> String {
65 Argon2::default()
66 .hash_password_with_salt(plain.as_bytes(), salt.as_bytes())
67 .expect("Argon2 hashing with a valid salt must succeed")
68 .to_string()
69}
70
71#[cfg(test)]
72mod tests {
73 use argon2::{PasswordHash, password_hash::phc::SaltString};
74
75 use super::{Argon2idPasswordHasher, PasswordHasher, hash_password_with_salt};
76 use crate::SecurityError;
77
78 #[test]
79 fn hash_verify_roundtrip_and_reject_wrong() {
80 let hasher = Argon2idPasswordHasher::new();
81 let encoded = hasher.hash("correct horse").expect("hash");
82 assert!(encoded.starts_with("$argon2id$"));
83 assert!(hasher.verify(&encoded, "correct horse").expect("ok"));
84 assert!(!hasher.verify(&encoded, "wrong").expect("mismatch"));
85 assert_ne!(hasher.hash("correct horse").expect("again"), encoded);
86 }
87
88 #[test]
89 fn empty_plain_rejected_and_bad_hash_errors() {
90 let hasher = Argon2idPasswordHasher;
91 assert!(matches!(
92 hasher.hash(""),
93 Err(SecurityError::Password { .. })
94 ));
95 assert!(matches!(
96 hasher.verify("not-a-phc", "x"),
97 Err(SecurityError::Password { .. })
98 ));
99 }
100
101 #[test]
102 fn hash_password_with_salt_produces_argon2_hash() {
103 let salt = SaltString::generate();
104
105 let hash = hash_password_with_salt("secret", &salt);
106
107 assert!(hash.starts_with("$argon2id$"));
108 assert!(PasswordHash::new(&hash).is_ok());
109 }
110}