shared-framework 0.0.18

Reusable building blocks for HTTP services — Hyper routing, SeaORM data layer, validation, OpenAPI docs, jobs, queues, cache.
Documentation
//! Password hashing and token generation.
//!
//! [`CryptoHelper`] hashes passwords with Argon2, verifies hashes, and creates
//! random alphanumeric tokens. Use it for storing credentials and issuing opaque tokens.
//!
//! ```ignore
//! let hash = CryptoHelper::hash_password("secret")?;
//! assert!(CryptoHelper::verify_password(&hash, "secret")?);
//! ```

use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier};

/// Password hashing (Argon2) and random token helpers.
pub struct CryptoHelper;

impl CryptoHelper {
    /// Hashes a password with Argon2. Returns an error if hashing fails.
    pub fn hash_password(password: &str) -> Result<String, argon2::password_hash::Error> {
        let argon2 = Argon2::default();
        Ok(argon2.hash_password(password.as_bytes())?.to_string())
    }

    /// Verifies a password against an Argon2 hash. Returns `Ok(false)` for a mismatch
    /// and an error when the stored hash cannot be parsed.
    pub fn verify_password(hash: &str, password: &str) -> Result<bool, argon2::password_hash::Error> {
        let parsed = PasswordHash::new(hash)?;
        Ok(Argon2::default().verify_password(password.as_bytes(), &parsed).is_ok())
    }

    /// Creates a random alphanumeric token of length `len`.
    pub fn random_token(len: usize) -> String {
        crate::utils::data_helpers::DataHelpers::create_token(len)
    }
}