How to create a MD5 hash of a word in android?

By | September 3, 2011

This is one of the most useful things in android.
We can use the MD5 algorithm to create a hash of any string we want.
Here is the code for doing that.
Check the LogCat for output.

package pack.coderzheaven;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.app.Activity;
import android.os.Bundle;

public class MD5Demo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        System.out.println("Hash Word : " + createHash("CoderzHeaven"));
    }

    static public String createHash(String word) {
    	   String created_hash = null;
    	   try {
    	      MessageDigest md5 = MessageDigest.getInstance("MD5");
    	      md5.update(word.getBytes());
    	      BigInteger hash = new BigInteger(1, md5.digest());
    	      created_hash = hash.toString(16);
    	   } catch (NoSuchAlgorithmException e) {
    	      System.out.println("Exception : " + e.getMessage());
    	   }
    	   return created_hash;
    	}
}

Please leave your valuable comments on this post.

Leave a Reply

Your email address will not be published. Required fields are marked *