password_hash/
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#![forbid(unsafe_code)]
9#![warn(
10    missing_docs,
11    rust_2018_idioms,
12    unused_lifetimes,
13    missing_debug_implementations
14)]
15
16//!
17//! # Usage
18//!
19//! This crate represents password hashes using the [`PasswordHash`] type, which
20//! represents a parsed "PHC string" with the following format:
21//!
22//! ```text
23//! $<id>[$v=<version>][$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
24//! ```
25//!
26//! For more information, please see the documentation for [`PasswordHash`].
27
28#[cfg(feature = "alloc")]
29#[allow(unused_extern_crates)]
30extern crate alloc;
31
32mod error;
33
34pub use crate::error::{Error, Result};
35
36#[cfg(feature = "phc")]
37pub use phc;
38
39#[cfg(feature = "rand_core")]
40pub use rand_core::{self, TryCryptoRng};
41
42/// DEPRECATED: import this as `password_hash::phc::PasswordHash`.
43#[cfg(feature = "phc")]
44#[deprecated(
45    since = "0.6.0",
46    note = "import as `password_hash::phc::PasswordHash` instead"
47)]
48pub type PasswordHash = phc::PasswordHash;
49
50/// DEPRECATED: use `password_hash::phc::PasswordHash` or `String`
51#[cfg(all(feature = "alloc", feature = "phc"))]
52#[deprecated(
53    since = "0.6.0",
54    note = "use `password_hash::phc::PasswordHash` or `String`"
55)]
56#[allow(deprecated)]
57pub type PasswordHashString = phc::PasswordHashString;
58
59use core::{
60    fmt::{Debug, Display},
61    str::FromStr,
62};
63
64/// Numeric version identifier for password hashing algorithms.
65pub type Version = u32;
66
67/// Recommended length of a salt: 16-bytes.
68///
69/// This recommendation comes from the [PHC string format specification]:
70///
71/// > The role of salts is to achieve uniqueness. A *random* salt is fine
72/// > for that as long as its length is sufficient; a 16-byte salt would
73/// > work well (by definition, UUID are very good salts, and they encode
74/// > over exactly 16 bytes). 16 bytes encode as 22 characters in B64.
75///
76/// [PHC string format specification]: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md#function-duties
77#[cfg(any(feature = "getrandom", feature = "rand_core"))]
78const RECOMMENDED_SALT_LEN: usize = 16;
79
80/// High-level trait for password hashing functions.
81///
82/// Generic around a password hash to be returned (typically [`phc::PasswordHash`])
83pub trait PasswordHasher<H> {
84    /// Compute the hash `H` from the given password and salt, potentially using configuration
85    /// stored in `&self` for the parameters, or otherwise the recommended defaults.
86    ///
87    /// The salt should be unique per password. When in doubt, use [`PasswordHasher::hash_password`]
88    /// which will choose the salt for you.
89    fn hash_password_with_salt(&self, password: &[u8], salt: &[u8]) -> Result<H>;
90
91    /// Compute the hash `H` from the given password, potentially using configuration stored in
92    /// `&self` for the parameters, or otherwise the recommended defaults.
93    ///
94    /// A large random salt will be generated automatically.
95    #[cfg(feature = "getrandom")]
96    fn hash_password(&self, password: &[u8]) -> Result<H> {
97        let mut salt = [0u8; RECOMMENDED_SALT_LEN];
98        getrandom::fill(&mut salt).map_err(|_| Error::Crypto)?;
99        self.hash_password_with_salt(password, &salt)
100    }
101
102    /// Compute the hash `H` from the given password, potentially using configuration stored in
103    /// `&self` for the parameters, or otherwise the recommended defaults.
104    ///
105    /// A large random salt will be generated automatically from the provided RNG.
106    #[cfg(feature = "rand_core")]
107    fn hash_password_with_rng<R: TryCryptoRng + ?Sized>(
108        &self,
109        rng: &mut R,
110        password: &[u8],
111    ) -> Result<H> {
112        let mut salt = [0u8; RECOMMENDED_SALT_LEN];
113        rng.try_fill_bytes(&mut salt).map_err(|_| Error::Crypto)?;
114        self.hash_password_with_salt(password, &salt)
115    }
116}
117
118/// Trait for password hashing functions which support customization.
119///
120/// Generic around a password hash to be returned (typically [`PasswordHash`])
121pub trait CustomizedPasswordHasher<H> {
122    /// Algorithm-specific parameters.
123    type Params: Clone + Debug + Default + Display + FromStr;
124
125    /// Compute a [`PasswordHash`] from the provided password using an
126    /// explicit set of customized algorithm parameters as opposed to the
127    /// defaults.
128    ///
129    /// When in doubt, use [`PasswordHasher::hash_password`] instead.
130    fn hash_password_customized(
131        &self,
132        password: &[u8],
133        salt: &[u8],
134        algorithm: Option<&str>,
135        version: Option<Version>,
136        params: Self::Params,
137    ) -> Result<H>;
138
139    /// Compute a [`PasswordHash`] using customized parameters only, using the default
140    /// algorithm and version.
141    fn hash_password_with_params(
142        &self,
143        password: &[u8],
144        salt: &[u8],
145        params: Self::Params,
146    ) -> Result<H> {
147        self.hash_password_customized(password, salt, None, None, params)
148    }
149}
150
151/// Trait for password verification.
152///
153/// Generic around a password hash to be returned (typically [`phc::PasswordHash`])
154///
155/// Automatically impl'd for type that impl [`PasswordHasher`] with [`phc::PasswordHash`] as `H`.
156///
157/// This trait is object safe and can be used to implement abstractions over
158/// multiple password hashing algorithms.
159pub trait PasswordVerifier<H: ?Sized> {
160    /// Compute this password hashing function against the provided password
161    /// using the parameters from the provided password hash and see if the
162    /// computed output matches.
163    fn verify_password(&self, password: &[u8], hash: &H) -> Result<()>;
164}
165
166#[cfg(feature = "phc")]
167impl<T: CustomizedPasswordHasher<phc::PasswordHash>, E> PasswordVerifier<phc::PasswordHash> for T
168where
169    T::Params: FromStr<Err = E>,
170    Error: From<E>,
171{
172    fn verify_password(&self, password: &[u8], hash: &phc::PasswordHash) -> Result<()> {
173        #[allow(clippy::single_match)]
174        match (&hash.salt, &hash.hash) {
175            (Some(salt), Some(expected_output)) => {
176                let computed_hash = self.hash_password_customized(
177                    password,
178                    salt,
179                    Some(hash.algorithm.as_str()),
180                    hash.version,
181                    T::Params::from_str(hash.params.as_str())?,
182                )?;
183
184                if let Some(computed_output) = &computed_hash.hash {
185                    // See notes on `Output` about the use of a constant-time comparison
186                    if expected_output == computed_output {
187                        return Ok(());
188                    }
189                }
190            }
191            _ => (),
192        }
193
194        Err(Error::PasswordInvalid)
195    }
196}
197
198/// Trait for password hashing algorithms which support the legacy
199/// [Modular Crypt Format (MCF)][MCF].
200///
201/// [MCF]: https://passlib.readthedocs.io/en/stable/modular_crypt_format.html
202#[cfg(feature = "phc")]
203pub trait McfHasher {
204    /// Upgrade an MCF hash to a PHC hash. MCF follow this rough format:
205    ///
206    /// ```text
207    /// $<id>$<content>
208    /// ```
209    ///
210    /// MCF hashes are otherwise largely unstructured and parsed according to
211    /// algorithm-specific rules so hashers must parse a raw string themselves.
212    fn upgrade_mcf_hash(&self, hash: &str) -> Result<phc::PasswordHash>;
213}