Search code examples
codenameone

Codename One MD5 method in Bouncy Castle Library


Referencing this older question, I am trying to generate a MD5 hash, but I am getting a result that is not similar to an outcome that this MD5 web generator gives.

Here is the code I am trying

String data = "XXXXXXXXXXXXX";
MD5Digest md5Digest = new MD5Digest();
try {
   byte[] b = data.getBytes("UTF-8");
   md5Digest.update(b, 0, b.length);
   byte[] hash = new byte[md5Digest.getDigestSize()];
   md5Digest.doFinal(hash, 0);

   signature = new String(hash, "UTF-8");
} catch (Exception ex) {
   Log.e(ex);
}

What is wrong?


Solution

  • They do produce the same output. It's just the website being obtuse about how the data is displayed. This is the output of the website:

    Website hash function

    The problem is that you just take the bytes and convert them to a String as is. But the website just lists the hexdecimal value of each byte as a two character string. E.g. if you stop in the debugger on the value and inspect it then it looks different but if you set the debugger to show the value as hexdecimal (available via the right click) then you see this:

    Debug inspector window

    This is the code you would need to produce the same output. Notice that I force two characters for every entry:

    StringBuilder builder = new StringBuilder();
    for(byte current : hash) {
        String val = Integer.toHexString(current & 0xff);
        if(val.length() < 2) {
            builder.append("0");
        }
        builder.append(val);
    }
    Log.p(builder.toString());