Java 生成16/32位 MD5

来源:互联网 发布:网络优化方案 分布式 编辑:程序博客网 时间:2024/05/12 18:02

注意!网上广为流传的MD5计算的版本,与标准MD5计算结果不同(原因可能是编码方式的不同)。请注意甄别。

以下代码是经过测试的正确版本。


private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };private static String toHexString(byte[] b) {    StringBuilder sb = new StringBuilder(b.length * 2);    for (int i = 0; i < b.length; i++) {        sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);        sb.append(HEX_DIGITS[b[i] & 0x0f]);    }    return sb.toString();}public static String Bit32(String SourceString) throws Exception {    MessageDigest digest = java.security.MessageDigest.getInstance("MD5");    digest.update(SourceString.getBytes());    byte messageDigest[] = digest.digest();    return toHexString(messageDigest);}public static String Bit16(String SourceString) throws Exception {    return Bit32(SourceString).substring(8, 24);}

0 0