MD5在Java中生成31个字符的哈希值

div*_*gon 12 java hash encoding md5

我使用以下代码块来生成MD5哈希:

public static String encode(String data) throws Exception {

    /* Check the validity of data */
    if (data == null || data.isEmpty()) {
        throw new IllegalArgumentException("Null value provided for "
                + "MD5 Encoding");
    }

    /* Get the instances for a given digest scheme MD5 or SHA */
    MessageDigest m = MessageDigest.getInstance("MD5");

    /* Generate the digest. Pass in the text as bytes, length to the
     * bytes(offset) to be hashed; for full string pass 0 to text.length()
     */
    m.update(data.getBytes(), 0, data.length());

    /* Get the String representation of hash bytes, create a big integer
     * out of bytes then convert it into hex value (16 as input to
     * toString method)
     */
    String digest = new BigInteger(1, m.digest()).toString(16);

    return digest;
}
Run Code Online (Sandbox Code Playgroud)

当我用String数据运行上面的代码段时[12, B006GQIIEM, MH-ANT2000],输出是一个31个字符的哈希 - 268d43a823933c9dafaa4ac0e756d6a.

MD5哈希函数有问题还是上面的代码有问题?

小智 8

你可以试试这个:

...
String digest = String.format("%032x", new BigInteger(1, m.digest()));
Run Code Online (Sandbox Code Playgroud)

注:这是"%032x"不是"%32x".


riz*_*z86 7

代码中唯一的问题是当MSB小于Ox10时,结果哈希字符串只有31个字节,而不是32个字节,缺少前导零.

以这种方式创建md5字符串:

            byte messageDigest[] = m.digest();

            hexString = new StringBuffer();
            for (int i=0;i<messageDigest.length;i++) {
                String hex=Integer.toHexString(0xFF & messageDigest[i]);
                if(hex.length()==1)
                    hexString.append('0');

                hexString.append(hex);
            }
Run Code Online (Sandbox Code Playgroud)

  • @ rizzz86:很抱歉,但你的评论有误导性,因为它与OP的代码无关,而是与你的有关.他使用`.toString(16)`并生成正确的十六进制表示,*它不会忘记在十六进制字符串中添加零* - 它只丢弃前导零.所以OP也可能以*为前缀*为必要*以获得32字节的字符串. (2认同)