I want to convert the following method to java. I want do not want to implement it myself. But I do not get expected encoded string. Here is the code:
QString CHMacMD5::MD5_encode(QString password) {
unsigned char result[16];
memset( result, 0, sizeof(result) );
QString md5key = "some_key";
CHMacMD5 md5;
md5.HMac_MD5(password.toUtf8().constData(),password.length(),md5key.toUtf8().constData(),md5key.length(),result);
QString md5out;
for( int i = 0; i < 16; ++i ) {
md5out += QString("%1").arg(result[i], 2, 16, QChar('0'));
}
return md5out;
}
I guess there is something happening between java string conversion to UTF-8, unsigned byte, etc.
Here is my java code:
private void md5Encode(String password) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return;
}
md.update(javaStringToNullTerminatedString(password));
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
System.out.println("original:" + password);
System.out.println("digested(hex):" + sb.toString());
}
private byte[] javaStringToNullTerminatedString(String string) {
CharsetEncoder enc = Charset.forName("ISO-8859-1").newEncoder();
int len = string.length();
byte b[] = new byte[len + 1];
ByteBuffer bbuf = ByteBuffer.wrap(b);
enc.encode(CharBuffer.wrap(string), bbuf, true);
b[len] = 0;
return b;
}