package com.muyu.web.utils;

import lombok.extern.log4j.Log4j2;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

@Log4j2
public class MD5Util {
    private static final Integer SALT_LENGTH = 12;

    /**
     * 指定数组转化为16进制字符串
     */
    public static String byteToHexString(byte[]b){
        StringBuilder stringBuilder = new StringBuilder();
        for (byte value : b) {
            String hex = Integer.toHexString(value & 0xFF);
            if (hex.length()==1){
                hex='0'+hex;
            }
            stringBuilder.append(hex.toUpperCase());
        }
        return stringBuilder.toString();
    }

    /**
     * 获得加密后的口令
     */
    public static String encrypted(String str){
        try {
        byte[]pwd=null;
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[SALT_LENGTH];
        random.nextBytes(salt);
        MessageDigest md=null;
        md = MessageDigest.getInstance("MD5");
        md.update(salt);
        md.update(str.getBytes(StandardCharsets.UTF_8));
        byte[] digest = md.digest();
        pwd=new byte[digest.length+SALT_LENGTH];
        System.arraycopy(salt,0,pwd,0,SALT_LENGTH);
        System.arraycopy(digest,0,pwd,SALT_LENGTH,digest.length);
        return byteToHexString(pwd);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

}
