package com.cool.store.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @Author: WangShuo
 * @Date: 2025/04/06/15:03
 * @Version 1.0
 * @注释:
 */
public class PasswordUtil {

    /**
     * 生成随机盐值
     *
     * @return 随机生成的盐值（字节数组）
     */
    public static byte[] generateSalt() {
        SecureRandom secureRandom = new SecureRandom();
        // 16 字节的盐值
        byte[] salt = new byte[3];
        secureRandom.nextBytes(salt);
        return salt;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    /**
     * 使用 MD5 加密密码
     *
     * @param plainPassword 明文密码
     * @param salt          盐值
     * @return 加密后的密码（十六进制字符串）
     */
    public static String encryptPassword(String plainPassword, String salt) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");

            String combined = plainPassword + salt;

            byte[] hashedBytes = messageDigest.digest(combined.getBytes());

            // 将字节数组转换为十六进制字符串
            return bytesToHex(hashedBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error encrypting password", e);
        }
    }
}
