Loading

Java中md5摘要算法的几种方法

public class MD5_Test {
    public static String md5_1(String oldStr) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] oldBytes = oldStr.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(oldBytes);
            byte[] newBytes = md.digest();
            char newStr[] = new char[32];
            for (int i = 0; i < 16; i++) {
                byte tmp = newBytes[i];
                newStr[2 * i] = hexDigits[tmp >>> 4 & 0xf];
                newStr[2 * i + 1] = hexDigits[tmp & 0xf];
            }
            return new String(newStr);
        } catch (Exception e) {
            return null;
        }
    }

    public static String md5_2(String oldStr) {
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] bs = digest.digest(oldStr.getBytes());
            String hexString = "";
            for (byte b : bs) {
                int temp = b & 255;
                if (temp < 16 && temp >= 0) {
                    hexString = hexString + "0" + Integer.toHexString(temp);
                } else {
                    hexString = hexString + Integer.toHexString(temp);
                }
            }
            return hexString;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String md5_3(String plainText) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(plainText.getBytes());
        byte b[] = md.digest();
        int i;
        StringBuffer buf = new StringBuffer("");
        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0)
                i += 256;
            if (i < 16)
                buf.append("0");
            buf.append(Integer.toHexString(i));
        }
        return buf.toString();
        // System.out.println("result: " + buf.toString());//32位的加密
        // System.out.println("result: " + buf.toString().substring(8,24));//16位的加密
    }

    public static String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        // 确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        // 加密后的字符串
        String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));

        return newstr;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        System.out.println(md5_1("1"));
        System.out.println(md5_2("1"));
        System.out.println(md5_2("1"));
    }
}

输出结果:

posted @ 2018-04-14 20:00  Convict  阅读(420)  评论(0编辑  收藏  举报