消息摘要工具类。集成了16位MD5、32位MD5、SHA1、SHA224、SHA256、SHA384、SHA512

/**
 * 消息摘要工具类。集成了16位MD5、32位MD5、SHA1、SHA224、SHA256、SHA384、SHA512;
 * @author 大别山人*/
public final class HashUtils {
    /**
     * 根据指定的字符串,返回SHA1的摘要结果
     * @param data    要生成摘要信息的字符串
     * @return
     */
    public static final String toSHA1(String data) {
        return compute(data, "SHA-1");
    }
    /**
     * 根据指定的字符串,返回SHA224的摘要结果
     * @param data    要生成摘要信息的字符串
     * @return
     */
    public static final String toSHA224(String data) {
        return compute(data, "SHA-224");
    }
    /**
     * 根据指定的字符串,返回SHA256的摘要结果
     * @param data    要生成摘要信息的字符串
     * @return
     */
    public static final String toSHA256(String data) {
        return compute(data, "SHA-256");
    }
    /**
     * 根据指定的字符串,返回SHA384的摘要结果
     * @param data    要生成摘要信息的字符串
     * @return
     */
    public static final String toSHA384(String data) {
        return compute(data, "SHA-384");
    }
    /**
     * 根据指定的字符串,返回SHA512的摘要结果
     * @param data    要生成摘要信息的字符串
     * @return
     */
    public static final String toSHA512(String data) {
        return compute(data, "SHA-512");
    }
    /**
     * 根据指定的字符串,返回32为MD5的摘要结果
     * @param data    要生成摘要信息的字符串
     * @return
     */
    public static final String toMD5_32(String data) {
        return compute(data, "md5");
    }
    /**
     * 根据指定的字符串,返回16位MD5的摘要结果
     * @param data    要生成摘要信息的字符串
     * @return
     */
    public static final String toMD5_16(String data) {
        return compute(data, "md5").substring(8, 24);
    }
    /**
     * 根据指定的字符串和指定的摘要算法,返回对应的摘要结果
     * @param data    要生成摘要信息的字符串
     * @param strType    指定的摘要算法
     * @return
     */
    private static final String compute(String data,String strType ) {
        try {
            MessageDigest digest = MessageDigest.getInstance(strType);
            digest.update(data.getBytes("utf-8"));
            byte[] bs = digest.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : bs) {
                int temp = b & 0xFF;
                if (temp < 16) {
                    sb.append("0");
                }
                sb.append(Integer.toHexString(temp));
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
原文地址:https://www.cnblogs.com/pf1988/p/8672267.html