package com.qmth.sop.common.util;

import com.qmth.sop.common.contant.SystemConstant;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
import java.util.StringJoiner;

/**
 * @Description: MD5加密工具类
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2019/10/11
 */
public class MD5Util {

    /**
     * MD5加密
     *
     * @param text
     * @return
     * @throws Exception
     */
    public static String encoder(String text) throws NoSuchAlgorithmException {
        text = Optional.of(text).get();
        MessageDigest digest = MessageDigest.getInstance(SystemConstant.MD5);
        digest.update(text.getBytes(SystemConstant.CHARSET));
        byte s[] = digest.digest();
        StringJoiner result = new StringJoiner("");
        for (int i = 0; i < s.length; i++) {
            result.add(Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00).substring(6));
        }
        return result.toString();
    }

    /**
     * MD5校验
     *
     * @param text
     * @param md5
     * @return
     * @throws Exception
     */
    public static boolean verify(String text, String md5) throws NoSuchAlgorithmException {
        text = Optional.of(text).get();
        md5 = Optional.of(md5).get();
        //根据传入的密钥进行验证
        String md5Text = encoder(text);
        if (md5Text.equalsIgnoreCase(md5)) {
            return true;
        }
        return false;
    }
}

