2

当我用 java 在 md5 中加密某些东西时,它会从哈希中删除所有的 0,这对我来说不好,因为它不适用于 php,因为 php 不会删除 0。有什么办法可以修复它(除了让 php 也删除 0)。这是我的java代码:

public String getMd5Hash(String str) {
    try {
        byte[] array = MessageDigest.getInstance("MD5").digest(str.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
        }
        return sb.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Something went really wrong.");
    }
    return null;
}
4

1 回答 1

1

Integer.toHexString 不会将零添加到您隐式想要的长度。使用带有“%02x”格式字符串的 java.util.Formatter 类将十六进制数字转换为您想要的格式。

下面的代码演示了这个问题。

import java.util.Formatter;

public class TestHex {

    public static final void main(String[]  args) {
        StringBuilder sb = new StringBuilder();
        Formatter formatter = new Formatter(sb);
        byte[] testbytes = {-127, 4, 64, -4};

        for (int i=0; i<testbytes.length; i++) {
            byte b = testbytes[i];
            System.out.printf("%s\t%s\n", formatter.format("%02x", b), Integer.toHexString(b & 0xff));
            sb.setLength(0);
        }
    }
}

运行时,这会产生:

81      81
04      4
40      40
fc      fc

请注意第二行,其中 Integer.toHexString 仅返回“4”,格式化程序为您提供所需的两位数。

于 2013-06-21T14:35:08.447 回答