package xyz.wbsite.frame.utils;

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

/**
 * MD5Util - MD5工具类
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
public class MD5Util {

    /**
     * 生成加密密码
     *
     * @param value 待加密字符串
     * @param salts 加密盐
     * @return 加密字符串
     */
    public static String generatePwd(String value, String... salts) {
        String pwd = encode(value);
        for (String s : salts) {
            pwd = encode(s + value + s);
        }
        return pwd;
    }

    /**
     * 生成加密密码
     *
     * @param value 待加密字符串
     * @return 加密字符串
     */
    public static String generatePwd(String value) {
        return generatePwd(value, "MD5");
    }

    /**
     * 加密字符串
     *
     * @param value 待加密字符串
     * @return 信息摘要Hex字符串
     */
    public static String encode(String value) {
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            byte[] e = md.digest(value.getBytes());
            return toHexString(e);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return value;
        }
    }

    /**
     * 加密字符串
     *
     * @param bytes 待加密字节数组
     * @return 信息摘要Hex字符串
     */
    public static String encode(byte[] bytes) {
        try {
            MessageDigest md = MessageDigest.getInstance("md5");
            byte[] e = md.digest(bytes);
            return toHexString(e);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * @param bytes 信息摘要字节数组
     * @return Hex字符串
     */
    private static String toHexString(byte bytes[]) {
        StringBuilder hs = new StringBuilder();
        String stmp = "";
        for (int n = 0; n < bytes.length; n++) {
            stmp = Integer.toHexString(bytes[n] & 0xff);
            if (stmp.length() == 1)
                hs.append("0").append(stmp);
            else
                hs.append(stmp);
        }

        return hs.toString();
    }
}
