package cn.com.qmth.stmms.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
import java.util.StringJoiner;

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

/**
 * @Description: MD5加密工具类
 */
public class MD5Util {
	public static final String CHARSET_NAME = "UTF-8";

    public static final Charset CHARSET = Charset.forName(CHARSET_NAME);
    
    public static final String MD5 = "MD5";

    /**
     * MD5加密
     *
     * @param text
     * @return
     * @throws Exception
     */
    public static String encoder(String text) throws NoSuchAlgorithmException {
        text = Optional.of(text).get();
        MessageDigest digest = MessageDigest.getInstance(MD5);
        digest.update(text.getBytes(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;
    }
    
	public static String md5Hex(File file) {
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			return DigestUtils.md5Hex(in);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if(in!=null)
				try {
					in.close();
				} catch (IOException e) {
				}
		}
	}
	
	public static String md5Hex(InputStream in) {
		try {
			return DigestUtils.md5Hex(in);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if(in!=null)
				try {
					in.close();
				} catch (IOException e) {
				}
		}
	}
}

