Sanket Kachhela
Sanket Kachhela

Reputation: 10876

MD5 hash in android or java

I required to convert string in MD5 hash.

I am using

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);

final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex( byte[] bytes )
    {
        char[] hexChars = new char[ bytes.length * 2 ];
        for( int j = 0; j < bytes.length; j++ )
        {
            int v = bytes[ j ] & 0xFF;
            hexChars[ j * 2 ] = hexArray[ v >>> 4 ];
            hexChars[ j * 2 + 1 ] = hexArray[ v & 0x0F ];
        }
        return new String( hexChars );
    }

It is giving output like this website http://www.md5.cz/

but I required to generate hash as this http://webcodertools.com/hashstring giving output.

Please use test in both sites.

with using above function I am getting o/p like first site but I need as second site is giving.

Is there any different function or am I missing something in this?

Thanks.

Upvotes: 1

Views: 4170

Answers (2)

MOSO
MOSO

Reputation: 393

Use this method it will return in the same format

public static String getMd5Hash(String input) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes());
        BigInteger number = new BigInteger(1, messageDigest);
        String md5 = number.toString(16);
        while (md5.length() < 32)
           md5 = "0" + md5;
        return md5;
        } catch (NoSuchAlgorithmException e) {
         Log.e("MD5", e.getLocalizedMessage());
      return null;
    }
    }

This returns in //4a2028eceac5e1f4d252ea13c71ecec6 format MD5 of "WHAT" and

String base64format =  Base64.encodeToString(thedigest, Base64.DEFAULT); //as given by @Jon Skeet

will return in the format as SiAo7OrF4fTSUuoTxx7Oxg==


Sorry for vice-versa solution.

Upvotes: -1

Jon Skeet
Jon Skeet

Reputation: 1503479

The second web site is simply using base64 instead of hex to represent the binary data as text. So you can get rid of your bytesToHex method entirely, and just use Base64:

String base64Digest = Base64.encodeToString(thedigest, Base64.DEFAULT);

(As an aside, I'd avoid using the as a prefix in variable names - it provides no benefit, and is just cruft.)

Upvotes: 3

Related Questions