package com.weiqi.mis;

import com.google.common.base.Charsets;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    /**
     * @Author : yyy
     * @Summary : md5
     * @Date : 2019/07/09 15:40
     */
    public final static byte[] md5(byte[] data) {
        Hasher hasher = Hashing.md5().newHasher();
        hasher.putBytes(data);
        return hasher.hash().asBytes();
    }

    /**
     * @Author : yyy
     * @Summary : md5
     * @Date : 2019/07/09 15:40
     */
    public final static String md5(String data) {
        Hasher hasher = Hashing.md5().newHasher();
        hasher.putString(data, Charsets.UTF_8);
        return hasher.hash().toString().toUpperCase();
    }


    public static void main(String[] args) {
        System.out.println(DigestUtils.md5DigestAsHex("abc".getBytes()));
        System.out.println(md5("abc").toLowerCase());
        //System.out.println(getMD5Str("abc"));
    }

    /**
     * description: 聚通达专用
     *
     * @param sourceStr
     * @return  java.lang.String
     */
    public static String getMD5(String sourceStr) {
        String resultStr = "";
        try {
            byte[] temp = sourceStr.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(temp);
            byte[] b = md5.digest();
            for (int i = 0; i < b.length; i++) {
                char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                        '9', 'A', 'B', 'C', 'D', 'E', 'F'};
                char[] ob = new char[2];
                ob[0] = digit[(b[i] >>> 4) & 0X0F];
                ob[1] = digit[b[i] & 0X0F];
                resultStr += new String(ob);
            }
            return resultStr;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}
