Skip to main content

password_auth/
lib.rs

1#![no_std]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![doc = include_str!("../README.md")]
4#![doc(
5    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
6    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg"
7)]
8
9extern crate alloc;
10
11mod errors;
12
13pub use crate::errors::{ParseError, VerifyError};
14
15use alloc::string::{String, ToString};
16use password_hash::{
17    PasswordHasher, PasswordVerifier,
18    phc::{ParamsString, PasswordHash},
19};
20
21#[cfg(not(any(feature = "argon2", feature = "pbkdf2", feature = "scrypt")))]
22compile_error!(
23    "please enable at least one password hash crate feature, e.g. argon2, pbkdf2, scrypt"
24);
25
26#[cfg(feature = "argon2")]
27use argon2::Argon2;
28#[cfg(feature = "pbkdf2")]
29use pbkdf2::Pbkdf2;
30#[cfg(feature = "scrypt")]
31use scrypt::Scrypt;
32
33/// Generate a password hash for the given password.
34///
35/// Uses the best available password hashing algorithm given the enabled crate features (typically
36/// Argon2 unless explicitly disabled).
37#[allow(clippy::missing_panics_doc, reason = "shouldn't panic in practice")]
38pub fn generate_hash(password: impl AsRef<[u8]>) -> String {
39    generate_phc_hash(password.as_ref())
40        .as_ref()
41        .map(ToString::to_string)
42        .expect("password hashing error")
43}
44
45/// Generate a PHC hash using the preferred algorithm.
46#[allow(unreachable_code)]
47fn generate_phc_hash(password: &[u8]) -> password_hash::Result<PasswordHash> {
48    //
49    // Algorithms below are in order of preference
50    //
51    #[cfg(feature = "argon2")]
52    return Argon2::default().hash_password(password);
53
54    #[cfg(feature = "scrypt")]
55    return Scrypt::default().hash_password(password);
56
57    #[cfg(feature = "pbkdf2")]
58    return Pbkdf2::default().hash_password(password);
59}
60
61/// Verify the provided password against the provided password hash.
62///
63/// # Errors
64/// Returns `Err(VerifyError)` if the hash didn't parse successfully or the password failed to
65/// verify against the hash.
66pub fn verify_password(password: impl AsRef<[u8]>, hash: &str) -> Result<(), VerifyError> {
67    let hash = PasswordHash::new(hash).map_err(ParseError::new)?;
68
69    let algs: &[&dyn PasswordVerifier<PasswordHash>] = &[
70        #[cfg(feature = "argon2")]
71        &Argon2::default(),
72        #[cfg(feature = "pbkdf2")]
73        &Pbkdf2::default(),
74        #[cfg(feature = "scrypt")]
75        &Scrypt::default(),
76    ];
77
78    for &alg in algs {
79        if alg.verify_password(password.as_ref(), &hash).is_ok() {
80            return Ok(());
81        }
82    }
83
84    Err(VerifyError::PasswordInvalid)
85}
86
87/// Determine if the given password hash is using the recommended algorithm and parameters.
88///
89/// This can be used by implementations which wish to lazily update their password hashes (i.e. by
90/// rehashing the password with [`generate_hash`]) to determine if such an update should be applied.
91///
92/// When the hash parses successfully, it will return one of the following:
93/// - `Ok(true)` if the hash *isn't* using the latest recommended algorithm/parameters.
94/// - `Ok(false)` if the hash *is* using the latest recommended algorithm/parameters.
95///
96/// # Errors
97/// Returns `Err(ParseError)` if the hash could not be parsed.
98#[allow(unreachable_code, reason = "feature gating")]
99pub fn is_hash_obsolete(hash: &str) -> Result<bool, ParseError> {
100    let hash = PasswordHash::new(hash).map_err(ParseError::new)?;
101
102    #[cfg(feature = "argon2")]
103    return Ok(hash.algorithm != argon2::Algorithm::default().ident()
104        || hash.params != default_params_string::<argon2::Params>());
105
106    #[cfg(feature = "scrypt")]
107    return Ok(hash.algorithm != scrypt::phc::ALG_ID
108        || hash.params != default_params_string::<scrypt::Params>());
109
110    #[cfg(feature = "pbkdf2")]
111    return Ok(hash.algorithm != pbkdf2::Algorithm::default().into()
112        || hash.params != default_params_string::<pbkdf2::Params>());
113
114    Ok(true)
115}
116
117fn default_params_string<T>() -> ParamsString
118where
119    T: Default + TryInto<ParamsString, Error = password_hash::Error>,
120{
121    T::default().try_into().expect("invalid default params")
122}
123
124#[cfg(test)]
125mod tests {
126    use super::{generate_hash, is_hash_obsolete, verify_password};
127
128    const EXAMPLE_PASSWORD: &str = "password";
129
130    #[test]
131    fn happy_path() {
132        let hash = generate_hash(EXAMPLE_PASSWORD);
133        assert!(verify_password(EXAMPLE_PASSWORD, &hash).is_ok());
134        assert!(verify_password("bogus", &hash).is_err());
135        assert!(!is_hash_obsolete(&hash).expect("hash can be parsed"));
136    }
137
138    #[cfg(feature = "argon2")]
139    mod argon2 {
140        use super::{EXAMPLE_PASSWORD, verify_password};
141
142        /// Argon2 hash for the string "password".
143        const EXAMPLE_HASH: &str = "$argon2i$v=19$m=65536,t=1,p=1$c29tZXNhbHQAAAAAAAAAAA$+r0d29hqEB0yasKr55ZgICsQGSkl0v0kgwhd+U3wyRo";
144
145        #[test]
146        fn verify() {
147            assert!(verify_password(EXAMPLE_PASSWORD, EXAMPLE_HASH).is_ok());
148            assert!(verify_password("bogus", EXAMPLE_HASH).is_err());
149        }
150    }
151
152    #[cfg(feature = "pbkdf2")]
153    mod pdkdf2 {
154        use super::verify_password;
155
156        /// PBKDF2 password test vector from the `pbkdf2` crate
157        const EXAMPLE_PASSWORD: &[u8] = b"passwordPASSWORDpassword";
158
159        /// PBKDF2 hash test vector from the `pbkdf2` crate
160        const EXAMPLE_HASH: &str = "$pbkdf2-sha256$i=4096,l=40\
161            $c2FsdFNBTFRzYWx0U0FMVHNhbHRTQUxUc2FsdFNBTFRzYWx0\
162            $NIyJ28vTKy8y2BS4EW6EzysXNH68GAAYHE4qH7jdU+HGNVGMfaxH6Q";
163
164        #[test]
165        fn verify() {
166            assert!(verify_password(EXAMPLE_PASSWORD, EXAMPLE_HASH).is_ok());
167            assert!(verify_password("bogus", EXAMPLE_HASH).is_err());
168        }
169    }
170
171    #[cfg(feature = "scrypt")]
172    mod scrypt {
173        use super::{EXAMPLE_PASSWORD, verify_password};
174
175        /// scrypt hash for the string "password".
176        const EXAMPLE_HASH: &str = "$scrypt$ln=16,r=8,p=1$aM15713r3Xsvxbi31lqr1Q$nFNh2CVHVjNldFVKDHDlm4CbdRSCdEBsjjJxD+iCs5E";
177
178        #[test]
179        fn verify() {
180            assert!(verify_password(EXAMPLE_PASSWORD, EXAMPLE_HASH).is_ok());
181            assert!(verify_password("bogus", EXAMPLE_HASH).is_err());
182        }
183    }
184}