1

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;
}
mdavid
  • 563
  • 6
  • 20
  • 1
    You've only shown the code you're converting from, not the java code that you say isn't working correctly. – Michael Jan 31 '16 at 11:08

1 Answers1

1

The original code is not calculating a plain MD5 checksum, but a message authentication code using the secret key in variable md5key and the input password.

Your code is calculating just the md5 hash of the password and not using the key at all.

The combination of the secret key and the input text to the input of MD5 (or other hash functions) the get the hmac is specified by RFC 2104: https://www.ietf.org/rfc/rfc2104.txt

Here (the 2nd answer) seems to be how to do that in Java: How to Generate HMAC MD5 In Android?

Community
  • 1
  • 1
Sami Sallinen
  • 3,203
  • 12
  • 16