使用javaAPI生成MD5摘要

方法很简单,直接贴junit测试代码:

@Test
    public void test() throws NoSuchAlgorithmException {
        String str = "123456";
        byte[] buf = str.getBytes();
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(buf);
        byte[] tmp = md5.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : tmp) {
            if (b >= 0 && b < 16)
                sb.append("0");
            sb.append(Integer.toHexString(b & 0xff));
        }
        System.out.println("md5 length:" + tmp.length + " result length:" + sb.toString().length());
        System.out.println(sb);
    }

结果如下:

e10adc3949ba59abbe56e057f20f883e

Process finished with exit code 0

linux命令,如下:

 echo -n 123456|md5sum
e10adc3949ba59abbe56e057f20f883e  -

echo命令的-n选项代表不换行


整理后,方法如下:

public String getMD5(String need2Encode) throws NoSuchAlgorithmException {
        byte[] buf = need2Encode.getBytes();
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(buf);
        byte[] tmp = md5.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : tmp) {
            if (b >= 0 && b < 16)
                sb.append("0");
            sb.append(Integer.toHexString(b & 0xff));
        }
        return sb.toString();
    }

参考博客:Java生成md5、java 32位md5加密类

你可能感兴趣的:(java)