cris
cris

Reputation: 79

comparing md5 hashing in android(java) and c#

I am doing md-5 hashing in both android and c# at the same time. But both the results should be the same for the same inputs. Is there any difference in the way its done in both the languages?

I get different outputs in both the cases. Here is the c# code for md-5 calculation:

//this method hashes the values sent to it using MD5
public static String hashwithmd5(String toHashMD5)
{
    byte[] keyArray;

    MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
    keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(toHashMD5));
    hashmd5.Clear();
    return Convert.ToBase64String(keyArray, 0, keyArray.Length); 
}

and here is the code for md5 in android using bouncycastle

public byte[] Hashing(String toHash) throws Exception{
    byte[] hashBytes = toHash.getBytes("UTF-8");
    EditText et = (EditText) findViewById(R.id.entry);
    org.bouncycastle.crypto.digests.MD5Digest digest = new org.bouncycastle.crypto.digests.MD5Digest();
    digest.reset();
    digest.update(hashBytes, 0, hashBytes.length);
    int length = digest.getDigestSize();
    byte[] md5 = new byte[length];
    digest.doFinal(md5, 0);
    et.setText(md5.toString());
    return md5;
}

the result of md5 in c# is :XUFAKrxLKna5cZ2REBfFkg==

the result of md5 in android is :[B@4053cf40

Upvotes: 1

Views: 2503

Answers (4)

Taranfx
Taranfx

Reputation: 10437

Erik is absolutely right. MD5 usage is near extinction, use any strong SHA

Upvotes: 0

Thomas Pornin
Thomas Pornin

Reputation: 74382

When you use this in Java:

byte[] md5 = new byte[length];
// ...
md5.toString()

you are not getting a representation of the byte values. You get the generic "string representation" of an object. Here, [B@4053cf40 basically means "array of bytes (that's for the '[B') which internally happens to be at address 4053cf40".

Use android.util.Base64 to convert your bytes to a Base64 encoded string.

Upvotes: 1

Richard Schneider
Richard Schneider

Reputation: 35477

@erik is correct. MD5 is no longer considered a "secure" hash; use SHA-256.

Upvotes: 0

Erik
Erik

Reputation: 91270

The C# code converts the hash to Base64, the java code does not. If you convert both raw hashes to e.g. hex strings, they'll be the same.

Upvotes: 8

Related Questions