I found a solution to this problem here.
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);
But it seems to have a bug, I can't figure out where or how it happens.
The problem is this part I think:
String hashedPass = new BigInteger(1, md.digest()).toString(16);
The output of above code gives for String:
String = "9a9cce201b492954f0b06abb081d0bb4";
Correct MD5 of above string = "0e67b8eb546c322eeb39153714162ceb",
The code above though gives = "e67b8eb546c322eeb39153714162ceb";
It seems leading zeros of a MD5 are missing.