简体   繁体   English

30个字符的md5摘要

[英]30 char md5 digest

I use the following code for generating md5 for blob data in database. 我使用以下代码为数据库中的Blob数据生成md5

md5Checksum.update(byte[] --- read from database);
String result = new BigInteger(1,md5Checksum.digest()).toString(16);

The checksum i obtain is varying in length(30-32) for different byte arrays. 对于不同的字节数组,我获得的校验和的长度(30-32)有所不同。 For 31 char length checksum, as I understood can be an effect of the removal of leading zeros. 据我所知,对于31个字符长度的校验和,可能是去除前导零的影响。 (I handled it by adding leading zeros) (我通过添加前导零来处理)

Can any one tell me why I am getting a 30 char hash in some cases? 有人可以告诉我为什么在某些情况下为什么会得到30个字符的哈希值吗?

Thanks, Mithun 谢谢Mithun

Do not convert a digest to a number! 不要将摘要转换为数字!

Use something like: 使用类似:

byte[] b = md5Checksum.digest();
// now convert these bytes to chars

There are many different methods to convert byte[] to HexStrings: 有很多不同的方法可以将byte []转换为HexStrings:

public class HexConverter {

    // thanks to http://www.rgagnon.com/javadetails/java-0596.html
    static private final String HEXES = "0123456789ABCDEF";

    public String toHex(byte[] raw) {
        if (raw == null) {
            return null;
        }
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }
}

or from Getting a File's MD5 Checksum in Java (this link also shows how to se DigestUtils from Apache Commons Codec) 或从Java中获取文件的MD5校验和 (此链接还显示了如何从Apache Commons Codec中获取DigestUtils)

public static String getMD5Checksum(String filename) throws Exception {
    byte[] b = createChecksum(filename);
    String result = "";

    for (int i=0; i < b.length; i++) {
        result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
    }
    return result;
}

There is a chance that the high n bits could be zero. 高n位有可能为零。 As you convert the byte[] to a number.If n=4,then you could lose one '0' char at the beginning. 当您将byte []转换为数字时。如果n = 4,那么您可能会在开头丢失一个'0'字符。 If n=8, then you lose '00' at the beginning of your md5 hex code. 如果n = 8,则在md5十六进制代码的开头丢失“ 00”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM