mycommon-utils 0.1.2

Common utilities library for database operations, Redis caching and system utilities
Documentation
use md5;
use rand::Rng;
///  生成指定长度的字符串
pub fn rand_s(length: usize) -> String {
    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
                            abcdefghijklmnopqrstuvwxyz\
                            0123456789)(*&^%$#@!~";
    let mut rng = rand::rng();

    let rand_string: String = (0..length)
        .map(|_| {
            let idx = rng.random_range(0..CHARSET.len());
            CHARSET[idx] as char
        })
        .collect();

    rand_string
}

// 将字节数组转换为十六进制字符串
fn bytes_to_hex(bytes: &[u8]) -> String {
    use std::fmt::Write;
    let mut result = String::new();
    for byte in bytes {
        write!(result, "{:02x}", byte).expect("Writing to String should not fail");
    }
    result
}

/// 密码加密加盐
pub fn encrypt_password_salt(password: &str, salt: &str) -> String {
    if salt.len() == 0 {
        return encrypt_password(password);
    }
    let combined = format!("{}$X7h{}", password, salt);
    let digest = md5::compute(combined);
    bytes_to_hex(&digest[..])
}

/// 密码加密不带盐
pub fn encrypt_password(password: &str) -> String {
    let digest = md5::compute(password);
    bytes_to_hex(&digest[..])
}