从 char[] 生成 MD5 散列
Generating a MD5 hash from a char[]
我找到了这个问题的解决方案 。
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 = "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());
我找到了这个问题的解决方案
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 = "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());