从char []生成MD5哈希

MH

我在这里找到了解决此问题的方法

private byte[] toBytes(char[] chars) {
    CharBuffer charBuffer = CharBuffer.wrap(chars);
    ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
    byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
            byteBuffer.position(), byteBuffer.limit());
    Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
    Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
    return bytes;
}

char[] stringChars = "String".toCharArray();
byte[] stringBytes = toBytes(stringChars);

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(stringBytes);
String stringHash = new BigInteger(1, md.digest()).toString(16);

Arrays.fill(stringChars, '\u0000');
Arrays.fill(stringBytes, (byte) 0);

但它似乎有一个错误,我不知道它在哪里或如何发生。

问题是我认为这一部分:

String hashedPass = new BigInteger(1, md.digest()).toString(16);

上面代码的输出给出String:

String = "9a9cce201b492954f0b06abb081d0bb4";
Correct MD5 of above string = "0e67b8eb546c322eeb39153714162ceb",
The code above though gives = "e67b8eb546c322eeb39153714162ceb";

似乎缺少MD5的前导零。

小凤李

您不必使用BigInteger此任务,只需编写一种将字节数组转换为十六进制字符串的方法即可。

static String hexEncode(byte [] data) {
    StringBuilder hex = new StringBuilder();
    for (byte b : data) hex.append(String.format("%02x", b));
    return hex.toString();
}

String hash = hexEncode(md.digest());

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章