package cn.com.qmth.stmms.ms.commons.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.LoggerFactory;

import java.util.Optional;

/**
 * @Description: MD5加密工具类
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2019/10/11
 */
public class MD5Util {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(MD5Util.class);

    /**
     * MD5加密
     *
     * @param text
     * @return
     * @throws Exception
     */
    public static String encoder(String text) {
        text = Optional.of(text).get();
        LOGGER.info("MD5加密前的文本:{}", text);
        String encodeStr = DigestUtils.md5Hex(text);
        LOGGER.info("MD5加密后的文本:{}", encodeStr);
        return encodeStr;
    }

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

    /**
     * 生成图片md5规则
     *
     * @param workId
     * @param subjectId
     * @param areaCode
     * @param examNumber
     * @param studentId
     * @return
     */
    public static String getImageRuleMd5(Long workId, int subjectId, String areaCode, String examNumber, Long studentId) {
        //暂不用Aes解密，因为没用到反解
        StringBuffer stringBuffer = new StringBuffer(String.valueOf(workId)).append(subjectId).append(areaCode).append(examNumber).append(studentId);
        String rule = stringBuffer.toString();
        LOGGER.info("rule:{},length:{}", rule, rule.length());
        if (rule.length() < 16) {
            rule = String.format("%016d", Long.parseLong(rule));
            LOGGER.info("rule补零后:{},length:{}", rule, rule.length());
        }
        return encoder(rule);
    }
}
