views:

146

answers:

2

Hi,

I have my passwords encoded in MD5 in C# and inserted in my DB.

MD5 MD5Hasher = MD5.Create();
byte[] PasswordHash = MD5Hasher.ComputeHash(Encoding.Unicode.GetBytes(PasswordText.Value));

PasswordHash is inserted as is and look like 0x09C09E5B52580E477514FA.......... for example.

In the blackberry app, I get the password, want to encode it to pass it to a web service that will compare both hashed password. The problem is my result is different from the MD5 I create in my Blackberry app.

password = Crypto.encodeStringMD5(password);

Then below my function:

    public static String encodeStringMD5(String s) throws Exception {
    byte[] bytes = s.getBytes();
    MD5Digest digest = new MD5Digest();
    digest.update(bytes, 0, bytes.length);
    int length = digest.getDigestLength();
    byte[] md5 = new byte[length];
    digest.getDigest(md5, 0, true);
    return convertToHex(md5);
}

private static String convertToHex(byte[] data) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < data.length; i++) {
        int halfbyte = (data[i] >>> 4) & 0x0F;
        int two_halfs = 0;
        do {
            if ((0 <= halfbyte) && (halfbyte <= 9))
                buf.append((char) ('0' + halfbyte));
            else
                buf.append((char) ('a' + (halfbyte - 10)));
            halfbyte = data[i] & 0x0F;
        } while(two_halfs++ < 1);
    }
    return buf.toString();
}

So it returns something like this: 07054da3aea1cc98377fe0..........

Any idea how I can get the same hashed password that I create with my C# function in the Blackberry?

Thank you!

+2  A: 

The getBytes() method of java String returns a different encoding than the Encoding.Unicode in .NET. You need to specify unambiguous encoding algorithms. Use UTF-8 for both platforms and you should be ok. You can also try providing a charset name to the getBytes method on the Java side; try getBytes("UTF-16")

GregS
I tried using byte[] bytes = s.getBytes("UTF-16BE"); because Encoding.Unicode returns UTF-16. It encodes, the result is different but still not the same. It looks like this: fba5ca8e004126fbcc108f.......... Its seems to be better, but probably a problem while converting in hexadecimal?
Dachmt
Just use UTF-8 in both programs. I don't know if it should be UTF-16LE, or maybe one of them is spitting out the Byte Order Mark.
GregS
A: 

GregS answered your question directly; but as an aside I would recommend against having the client create the MD5 sum. If the server manages creating the MD5sum, you can further ensure that the password can't be reverse engineered (eg rainbow table) by adding a "salt" value to the password before encoding it on the server. If you do that on the client, you must expose the salt to the client which is less secure.

Marc Paradise