Skip to main content

hash

Function hash 

Source
pub fn hash(password: Password, rounds: Option<u32>) -> String
Expand description

Hash a password with a freshly generated, cryptographically secure random salt.

This is the recommended high-level API for storing new passwords.

§Arguments

  • password — Password to hash. Its buffer is zeroed before return.
  • rounds — Optional iteration count:
    • None uses the SHA-crypt default of 5000 rounds and omits the rounds= segment from the output.
    • Some(n) records rounds=n$ in the output, with n clamped into [1000, 999_999_999] per the SHA-crypt specification. Note that Some(5000) also omits the rounds= segment, so its output is bytewise identical to None.

§Returns

A complete hash string of the form $6$[rounds=N$]salt$hash.

§Panics

Panics (or aborts) if the active backend’s CSPRNG fails. All four backends treat CSPRNG failure as fatal rather than returning a predictable salt:

  • backend-aws-lc / backend-boring: the FFI RAND_bytes aborts the process when entropy is unavailable.
  • backend-openssl: this crate asserts the RAND_bytes return code.
  • backend-rust-crypto: this crate expects the getrandom call.

§Security

  • Salt is drawn from the active backend’s CSPRNG.
  • Password and intermediate hash buffers are wiped via the backend’s non-elidable zeroing primitive before this function returns.

§Examples

use crypt_sha512::{hash, verify, Password};

let h = hash(Password::from("hunter2"), None);
assert_eq!(verify(Password::from("hunter2"), &h), Ok(true));

// Higher work factor for sensitive deployments
let h = hash(Password::from("hunter2"), Some(100_000));
assert_eq!(verify(Password::from("hunter2"), &h), Ok(true));