package com.zcxk.core.utils.encrypt;

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

/**
 * @author Andy
 * @description: Md5
 * @date 2021/7/16
 * @version V1.0
 **/
public class Md5 {

    public static String digest(String inbuf) {
        try {
            MessageDigest md = MessageDigest.getInstance("Md5");
            md.update(inbuf.getBytes());
            byte[]  bypes= md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < bypes.length; offset++) {
                i = bypes[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
//            buf.toString();// 32位
//            buf.toString().substring(8, 24));// 16位
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String[] chars = new String[]{"a", "b", "c", "d", "e", "f",
        "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
        "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
        "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
        "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
        "W", "X", "Y", "Z"};

    /**
     * 根据加密后的MD5生成8位字符串
     * @param str
     * @return
     */
    public static String generateShort(String str) {
        StringBuffer shortBuffer = new StringBuffer();
        String digStr = digest(str);
        for (int i = 0; i < 8; i++) {
            String newStr = digStr.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(newStr, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

    private static byte[] md5(String s){
        MessageDigest algorithm;
        try{
            algorithm = MessageDigest.getInstance("Md5");
            algorithm.reset();
            algorithm.update(s.getBytes("UTF-8"));
            byte[] messageDigest = algorithm.digest();
            return messageDigest;
        }
        catch (Exception e){
        }
        return null;
    }

    private static final String toHex(byte[] hash){
        if (hash == null){
            return null;
        }
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;

        for (i = 0; i < hash.length; i++){
            if ((hash[i] & 0xff) < 0x10){
                buf.append("0");
            }
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    public static String hash(String s){
        try{
            return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
        }
        catch (Exception e){
            return s;
        }
    }
}
