pub fn verify(password: Password, hash: &str) -> Result<bool, InvalidHash>Expand description
Verify a password against a SHA512-crypt ($6$) hash using constant-time
comparison.
Extracts the salt (and rounds, if present) from hash, recomputes the
SHA512-crypt of password using that salt, and compares the result to
hash with the active backend’s constant-time comparison primitive.
§Arguments
password— Password to check. Its buffer is zeroed before return, regardless of which branch is taken (match, mismatch, or parse error).hash— Expected hash string in the format$6$[rounds=N$]salt$encoded_digest.
§Returns
Ok(true)—hashis well-formed andpasswordmatches it.Ok(false)—hashis well-formed andpassworddoes not match.Err(InvalidHash)—hashis not a well-formed$6$…$…string. No password comparison was performed.
§Errors
Returns InvalidHash if hash does not begin with $6$ or contains
no $ separating the salt from the encoded digest.
§Panics
Does not panic.
§Security
- Final comparison is constant-time (active backend’s primitive).
- Password buffer is zeroed via the backend’s non-elidable zeroing primitive before return on every code path, including the malformed-hash early returns.
§Examples
use crypt_sha512::{hash, verify, InvalidHash, Password};
let h = hash(Password::from("correct horse battery staple"), None);
assert_eq!(verify(Password::from("correct horse battery staple"), &h), Ok(true));
assert_eq!(verify(Password::from("Tr0ub4dor&3"), &h), Ok(false));
// Malformed hash strings are surfaced as Err, not Ok(false).
assert_eq!(verify(Password::from("anything"), "not a hash"), Err(InvalidHash));
// Works with any externally-produced $6$ hash:
let h = "$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1";
assert_eq!(verify(Password::from("Hello world!"), h), Ok(true));