package com.ssyf.common.core.helper;

import cn.hutool.crypto.SecureUtil;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 密码工具
 *
 * @author huwei
 * @date 2022/7/19 21:01
 */
public class PasswordHelper {
    /**
     * 盐值长度
     */
    private static final int SALT_LENGTH = 6;

    /**
     * 密码编码
     * @param password
     * @return
     */
    public static final String encode(String password) {
        //创建随机盐值
        SecureRandom secureRandom = new SecureRandom();
        byte[] saltBytes = new byte[SALT_LENGTH];
        secureRandom.nextBytes(saltBytes);
        return encode(saltBytes ,password.getBytes());
    }

    /**
     * 校验
     * @param password
     * @param encodeString
     * @return
     */
    public static final boolean valid(String password ,String encodeString){
        //base64解密编译过的字符
        byte[] encrypt = Base64.getDecoder().decode(encodeString);
        //获取盐值
        byte[] salt = new byte[SALT_LENGTH];
        System.arraycopy(encrypt, 0, salt, 0, SALT_LENGTH);
        return encodeString.equals(encode(salt ,password.getBytes()));
    }

    /**
     * 盐值编码
     * @param saltBytes
     * @param dataBytes
     * @return
     */
    private static final String encode(byte[] saltBytes ,byte[] dataBytes){
        byte[] srcBytes = new byte[saltBytes.length + dataBytes.length];
        System.arraycopy(saltBytes, 0, srcBytes, 0, saltBytes.length);
        System.arraycopy(dataBytes, 0, srcBytes, saltBytes.length, dataBytes.length);
        //加密
        MessageDigest md = SecureUtil.md5().getDigest();
        md.update(srcBytes);
        byte[] encryptBytes = md.digest();
        //封装盐值
        byte[] res = new byte[encryptBytes.length + saltBytes.length];
        System.arraycopy(saltBytes, 0, res, 0, saltBytes.length);
        System.arraycopy(encryptBytes, 0, res, saltBytes.length, encryptBytes.length);
        return Base64.getEncoder().encodeToString(res);
    }

}
