Skip to main content

Hash

Struct Hash 

Source
#[non_exhaustive]
pub struct Hash { /* private fields */ }
Expand description

Stores a hashed password together with its salt and the algorithm used.

Internal fields are private and zeroed on drop. Use the hash, salt, and algorithm accessors to read them.

Implementations§

Source§

impl Hash

Source

pub fn new_argon2id(password: &str, salt: Salt) -> Result<Self>

Creates a new Hash using Argon2id — the recommended variant.

§Errors

Returns Error::Decode if salt is not valid UTF-8, or Error::Hashing if the underlying argon2 crate rejects the parameters (output buffer too small, salt too short, etc.).

§Examples
use hsh::models::hash::{Hash, Salt};

let salt: Salt = b"abcdefghijklmnop".to_vec();
let h = Hash::new_argon2id("correct horse battery staple", salt)?;
assert!(!h.hash().is_empty());
Source

pub fn new_argon2i(password: &str, salt: Salt) -> Result<Self>

👎Deprecated since 0.0.9:

Argon2i is verify-only — use Hash::new_argon2id for new hashes.

Creates a new Hash using Argon2i.

Verify-only for legacy hashes — Argon2i is not recommended for new password hashes. Prefer Hash::new_argon2id.

Available only with the compat-v0_0_x feature. Slated for removal in v0.2.0 per the API stability contract.

Source

pub fn new_bcrypt(password: &str, cost: u32) -> Result<Self>

Creates a new Hash using Bcrypt at the given cost.

§Errors

Returns Error::InvalidPassword if the password exceeds 72 bytes (the bcrypt input limit — CVE-2025-22228 class) and the safety rail is engaged. Use crate::algorithms::bcrypt::BcryptParams::with_prehash for explicit handling of longer inputs. Returns Error::Hashing if the underlying bcrypt crate reports a primitive failure.

Source

pub fn new_scrypt(password: &str, salt: Salt) -> Result<Self>

Creates a new Hash using Scrypt with OWASP-2025 default params.

§Errors

Returns Error::Decode if salt is not valid UTF-8, or Error::Hashing if the underlying scrypt crate rejects the parameter set (output buffer too small, N not a power of two, etc.).

Source

pub fn algorithm(&self) -> HashAlgorithm

Returns the hashing algorithm used by this hash.

Source

pub fn from_hash(hash: &[u8], algo: &str) -> Result<Self>

Builds a Hash from existing hash bytes and an algorithm tag.

§Errors

Returns Error::UnsupportedAlgorithm if algo is not one of the recognised tags (argon2id, argon2i, argon2d, bcrypt, scrypt, pbkdf2, pbkdf2-sha256, pbkdf2-sha512).

Source

pub fn from_string(hash_str: &str) -> Result<Self>

Parses the legacy $algo$...$hash serialized form.

Not PHC-compliant — kept for backwards compatibility with pre-0.0.9 stored hashes. New code should round-trip through crate::api::hash / crate::api::verify_and_upgrade which emit RustCrypto-compatible PHC strings.

§Errors

Returns Error::InvalidHashString if the string doesn’t have the expected six $-separated fields, Error::UnsupportedAlgorithm if the algorithm tag isn’t recognised, or Error::Decode if the trailing base64 hash field is malformed.

Source

pub fn generate_hash(password: &str, salt: &str, algo: &str) -> Result<Vec<u8>>

Generates a raw hash for password with the given salt and algorithm tag. Returns the raw bytes only; for the storable form build a Hash and call Hash::to_string_representation, or use crate::api::hash for the modern PHC-formatted output.

§Errors

Returns Error::UnsupportedAlgorithm for an unrecognised tag, or any Error variant the underlying primitive emits — see the per-algorithm hash_with documentation in crate::algorithms.

Source

pub fn generate_random_string(len: usize) -> Result<String>

Generates a random alphanumeric string of length len from the OS CSPRNG (getrandom::getrandom). Suitable for human-readable Argon2 salts.

§Errors

Returns Error::Hashing if getrandom::getrandom fails — in practice this only happens when the OS entropy source isn’t available (very early boot, hardened sandbox without /dev/urandom).

Source

pub fn generate_salt(algo: &str) -> Result<String>

Generates a salt suitable for the named algorithm using the OS CSPRNG. Returns a UTF-8 string ready for storage.

§Errors

Returns Error::UnsupportedAlgorithm if algo isn’t one of "argon2id", "argon2i", "argon2d", "bcrypt", or "scrypt"; Error::Hashing if the OS CSPRNG fails.

Source

pub fn hash(&self) -> &[u8]

Returns the hash bytes.

Source

pub fn hash_length(&self) -> usize

Returns the length of the hash bytes.

Source

pub fn new(password: &str, salt: &str, algo: &str) -> Result<Self>

Builds a Hash from a password, salt, and algorithm tag.

Recognised tags: "argon2id" (recommended), "argon2i", "argon2d", "bcrypt", "scrypt", "pbkdf2", "pbkdf2-sha256", "pbkdf2-sha512".

§Errors

Returns Error::InvalidPassword if password.len() < 8, Error::UnsupportedAlgorithm for an unknown tag, or any Error variant the underlying primitive emits.

Source

pub fn parse(input: &str) -> Result<Self>

Parses a JSON string into a Hash.

§Errors

Returns Error::Decode wrapping a serde_json::Error if the input isn’t a valid serialised Hash.

Source

pub fn parse_algorithm(hash_str: &str) -> Result<HashAlgorithm>

Extracts the algorithm marker from a legacy serialized hash string.

§Errors

Returns Error::InvalidHashString if there’s no $-delimited algorithm field, or Error::UnsupportedAlgorithm if the field is present but unrecognised.

Source

pub fn salt(&self) -> &[u8]

Returns the salt bytes.

Source

pub fn set_hash(&mut self, hash: &[u8])

Sets the hash bytes, zeroing the previous buffer first.

Source

pub fn set_password( &mut self, password: &str, salt: &str, algo: &str, ) -> Result<()>

Re-hashes password with salt under algo and replaces the stored hash. The previous buffer is zeroized before replacement.

§Errors

Returns any Error variant that Self::generate_hash may emit (UnsupportedAlgorithm for an unknown tag, or any primitive-level failure from the underlying KDF).

Source

pub fn set_salt(&mut self, salt: &[u8])

Sets the salt bytes, zeroing the previous buffer first.

Source

pub fn to_string_representation(&self) -> String

Returns a non-PHC salt:hex debug string.

Source

pub fn verify(&self, password: &str) -> Result<bool>

Verifies password against this hash.

Constant-time: the byte comparison uses subtle::ConstantTimeEq. The bcrypt path delegates to the bcrypt crate, which also uses subtle internally.

Returns Ok(true) for a match, Ok(false) for a mismatch, or an Error if the stored material is malformed.

Trait Implementations§

Source§

impl Clone for Hash

Source§

fn clone(&self) -> Hash

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Hash

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Hash

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Hash

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Hash

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

impl Eq for Hash

Source§

impl Hash for Hash

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Hash

Source§

fn cmp(&self, other: &Hash) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Hash

Source§

fn eq(&self, other: &Hash) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for Hash

Source§

fn partial_cmp(&self, other: &Hash) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Hash

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Hash

Auto Trait Implementations§

§

impl Freeze for Hash

§

impl RefUnwindSafe for Hash

§

impl Send for Hash

§

impl Sync for Hash

§

impl Unpin for Hash

§

impl UnsafeUnpin for Hash

§

impl UnwindSafe for Hash

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.