1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
//! This crate defines a set of traits which describe the functionality of
//! [password hashing algorithms].
//!
//! Provides a `no_std`-friendly implementation of the
//! [Password Hashing Competition (PHC) string format specification][PHC]
//! (a well-defined subset of the [Modular Crypt Format a.k.a. MCF][MCF]) which
//! works in conjunction with the traits this crate defines.
//!
//! # Supported Crates
//!
//! See [RustCrypto/password-hashes] for algorithm implementations which use
//! this crate for interoperability:
//!
//! - [`argon2`] - Argon2 memory hard key derivation function
//! - [`pbkdf2`] - Password-Based Key Derivation Function v2
//! - [`scrypt`] - scrypt key derivation function
//!
//! # Usage
//!
//! This crate represents password hashes using the [`PasswordHash`] type, which
//! represents a parsed "PHC string" with the following format:
//!
//! ```text
//! $<id>[$v=<version>][$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
//! ```
//!
//! For more information, please see the documentation for [`PasswordHash`].
//!
//! [password hashing algorithms]: https://en.wikipedia.org/wiki/Cryptographic_hash_function#Password_verification
//! [PHC]: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md
//! [MCF]: https://passlib.readthedocs.io/en/stable/modular_crypt_format.html
//! [RustCrypto/password-hashes]: https://github.com/RustCrypto/password-hashes
//! [`argon2`]: https://docs.rs/argon2
//! [`pbkdf2`]: https://docs.rs/pbkdf2
//! [`scrypt`]: https://docs.rs/scrypt
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_root_url = "https://docs.rs/password-hash/0.3.0"
)]
#![forbid(unsafe_code)]
#![warn(missing_docs, rust_2018_idioms)]
#[cfg(all(feature = "alloc", test))]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "rand_core")]
#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
pub use rand_core;
pub mod errors;
mod encoding;
mod ident;
mod output;
mod params;
mod salt;
mod traits;
mod value;
pub use crate::{
encoding::Encoding,
errors::{Error, Result},
ident::Ident,
output::Output,
params::ParamsString,
salt::{Salt, SaltString},
traits::{McfHasher, PasswordHasher, PasswordVerifier},
value::{Decimal, Value},
};
use core::{
convert::{TryFrom, TryInto},
fmt::{self, Debug},
};
/// Separator character used in password hashes (e.g. `$6$...`).
const PASSWORD_HASH_SEPARATOR: char = '$';
/// Password hash.
///
/// This type corresponds to the parsed representation of a PHC string as
/// described in the [PHC string format specification][1].
///
/// PHC strings have the following format:
///
/// ```text
/// $<id>[$v=<version>][$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
/// ```
///
/// where:
///
/// - `<id>` is the symbolic name for the function
/// - `<version>` is the algorithm version
/// - `<param>` is a parameter name
/// - `<value>` is a parameter value
/// - `<salt>` is an encoding of the salt
/// - `<hash>` is an encoding of the hash output
///
/// The string is then the concatenation, in that order, of:
///
/// - a `$` sign;
/// - the function symbolic name;
/// - optionally, a `$` sign followed by the algorithm version with a `v=version` format;
/// - optionally, a `$` sign followed by one or several parameters, each with a `name=value` format;
/// the parameters are separated by commas;
/// - optionally, a `$` sign followed by the (encoded) salt value;
/// - optionally, a `$` sign followed by the (encoded) hash output (the hash output may be present
/// only if the salt is present).
///
/// [1]: https://github.com/P-H-C/phc-string-format/blob/master/phc-sf-spec.md#specification
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PasswordHash<'a> {
/// Password hashing algorithm identifier.
///
/// This corresponds to the `<id>` field in a PHC string, a.k.a. the
/// symbolic name for the function.
pub algorithm: Ident<'a>,
/// Optional version field.
///
/// This corresponds to the `<version>` field in a PHC string.
pub version: Option<Decimal>,
/// Algorithm-specific parameters.
///
/// This corresponds to the set of `$<param>=<value>(,<param>=<value>)*`
/// name/value pairs in a PHC string.
pub params: ParamsString,
/// [`Salt`] string for personalizing a password hash output.
///
/// This corresponds to the `<salt>` value in a PHC string.
pub salt: Option<Salt<'a>>,
/// Password hashing function [`Output`], a.k.a. hash/digest.
///
/// This corresponds to the `<hash>` output in a PHC string.
pub hash: Option<Output>,
}
impl<'a> PasswordHash<'a> {
/// Parse a password hash from a string in the PHC string format.
pub fn new(s: &'a str) -> Result<Self> {
Self::parse(s, Encoding::B64)
}
/// Parse a password hash from the given [`Encoding`].
pub fn parse(s: &'a str, encoding: Encoding) -> Result<Self> {
if s.is_empty() {
return Err(Error::PhcStringTooShort);
}
let mut fields = s.split(PASSWORD_HASH_SEPARATOR);
let beginning = fields.next().expect("no first field");
if beginning.chars().next().is_some() {
return Err(Error::PhcStringInvalid);
}
let algorithm = fields
.next()
.ok_or(Error::PhcStringTooShort)
.and_then(Ident::try_from)?;
let mut version = None;
let mut params = ParamsString::new();
let mut salt = None;
let mut hash = None;
let mut next_field = fields.next();
if let Some(field) = next_field {
// v=<version>
if field.starts_with("v=") && !field.contains(params::PARAMS_DELIMITER) {
version = Some(Value::new(&field[2..]).and_then(|value| value.decimal())?);
next_field = None;
}
}
if next_field.is_none() {
next_field = fields.next();
}
if let Some(field) = next_field {
// <param>=<value>
if field.contains(params::PAIR_DELIMITER) {
params = field.parse()?;
next_field = None;
}
}
if next_field.is_none() {
next_field = fields.next();
}
if let Some(s) = next_field {
salt = Some(s.try_into()?);
}
if let Some(field) = fields.next() {
hash = Some(Output::decode(field, encoding)?);
}
if fields.next().is_some() {
return Err(Error::PhcStringTooLong);
}
Ok(Self {
algorithm,
version,
params,
salt,
hash,
})
}
/// Generate a password hash using the supplied algorithm.
pub fn generate(
phf: impl PasswordHasher,
password: impl AsRef<[u8]>,
salt: &'a str,
) -> Result<Self> {
phf.hash_password(password.as_ref(), salt)
}
/// Verify this password hash using the specified set of supported
/// [`PasswordHasher`] trait objects.
pub fn verify_password(
&self,
phfs: &[&dyn PasswordVerifier],
password: impl AsRef<[u8]>,
) -> Result<()> {
for &phf in phfs {
if phf.verify_password(password.as_ref(), self).is_ok() {
return Ok(());
}
}
Err(Error::Password)
}
/// Get the [`Encoding`] that this [`PasswordHash`] is serialized with.
pub fn encoding(&self) -> Encoding {
self.hash.map(|h| h.encoding()).unwrap_or_default()
}
}
// Note: this uses `TryFrom` instead of `FromStr` to support a lifetime on
// the `str` the value is being parsed from.
impl<'a> TryFrom<&'a str> for PasswordHash<'a> {
type Error = Error;
fn try_from(s: &'a str) -> Result<Self> {
Self::new(s)
}
}
impl<'a> fmt::Display for PasswordHash<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", PASSWORD_HASH_SEPARATOR, self.algorithm)?;
if let Some(version) = self.version {
write!(f, "{}v={}", PASSWORD_HASH_SEPARATOR, version)?;
}
if !self.params.is_empty() {
write!(f, "{}{}", PASSWORD_HASH_SEPARATOR, self.params)?;
}
if let Some(salt) = &self.salt {
write!(f, "{}{}", PASSWORD_HASH_SEPARATOR, salt)?;
}
if let Some(hash) = &self.hash {
write!(f, "{}{}", PASSWORD_HASH_SEPARATOR, hash)?;
}
Ok(())
}
}