baichun-framework-core 0.1.0

Core module for Baichun-Rust framework
Documentation
use std::time::{SystemTime, UNIX_EPOCH};

use bcrypt::{hash, verify, DEFAULT_COST};
use hmac::{Hmac, Mac};
use jwt::{SignWithKey, VerifyWithKey};
use rand::{distributions::Alphanumeric, Rng};
use sha2::Sha256;
use uuid::Uuid;

use crate::error::{Error, Result};

/// 密码工具
pub struct PasswordUtils;

impl PasswordUtils {
    /// 生成密码哈希
    pub fn hash_password(password: &str) -> Result<String> {
        hash(password, DEFAULT_COST).map_err(|e| Error::System(e.to_string()))
    }

    /// 验证密码
    pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
        verify(password, hash).map_err(|e| Error::System(e.to_string()))
    }

    /// 生成随机密码
    pub fn generate_password(length: usize) -> String {
        rand::thread_rng()
            .sample_iter(&Alphanumeric)
            .take(length)
            .map(char::from)
            .collect()
    }
}

/// Token工具
pub struct TokenUtils;

impl TokenUtils {
    /// 生成JWT Token
    pub fn generate_token<T: serde::Serialize>(claims: &T, secret: &str) -> Result<String> {
        let key: Hmac<Sha256> =
            Hmac::new_from_slice(secret.as_bytes()).map_err(|e| Error::System(e.to_string()))?;
        claims
            .sign_with_key(&key)
            .map_err(|e| Error::System(e.to_string()))
    }

    /// 验证JWT Token
    pub fn verify_token<T: serde::de::DeserializeOwned>(token: &str, secret: &str) -> Result<T> {
        let key: Hmac<Sha256> =
            Hmac::new_from_slice(secret.as_bytes()).map_err(|e| Error::System(e.to_string()))?;
        token
            .verify_with_key(&key)
            .map_err(|e| Error::System(e.to_string()))
    }

    /// 生成UUID
    pub fn generate_uuid() -> String {
        Uuid::new_v4().to_string()
    }

    /// 获取当前时间戳(秒)
    pub fn current_timestamp() -> i64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64
    }
}

/// 加密工具
pub struct CryptoUtils;

impl CryptoUtils {
    /// 生成随机字符串
    pub fn random_string(length: usize) -> String {
        rand::thread_rng()
            .sample_iter(&Alphanumeric)
            .take(length)
            .map(char::from)
            .collect()
    }

    /// 计算SHA256哈希
    pub fn sha256(data: &[u8]) -> Vec<u8> {
        use sha2::Digest;
        let mut hasher = Sha256::new();
        hasher.update(data);
        hasher.finalize().to_vec()
    }

    /// 生成HMAC签名
    pub fn hmac_sign(key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
        let mut mac =
            Hmac::<Sha256>::new_from_slice(key).map_err(|e| Error::System(e.to_string()))?;
        mac.update(data);
        Ok(mac.finalize().into_bytes().to_vec())
    }

    /// 验证HMAC签名
    pub fn hmac_verify(key: &[u8], data: &[u8], signature: &[u8]) -> Result<bool> {
        let mut mac =
            Hmac::<Sha256>::new_from_slice(key).map_err(|e| Error::System(e.to_string()))?;
        mac.update(data);
        Ok(mac.verify_slice(signature).is_ok())
    }
}