January 10, 2010

Java Bouncycastle MD5

MD5 is one of a well known message digest/ hash algorithm. There are many websites where you can download free MD5 software but if you would like to build your own customize application, you can use Java open source library: bouncycastle.

Here is one of simple code that demonstrates how to utilize the bouncycastle library for MD5 algorithm.

import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.*;
import org.bouncycastle.crypto.digests.*;

/**
* @author http://myprogramminglab.blogspot.com/
*/

public class md5hash {
    public static void main(String[] args) {
        //add the security provider
        //not required if you have Install the library
        //by Configuring the Java Runtime
        Security.addProvider(new BouncyCastleProvider());

        //this is the input;
        byte input[] = {0x00, 0x01, 0x02, 0x03, 0x04};

        //update the input of MD5
        MD5Digest md5 = new MD5Digest();
        md5.update(input, 0, input.length);

        //get the output/ digest size and hash it
        byte[] digest = new byte[md5.getDigestSize()];
        md5.doFinal(digest, 0);

        //show the input and output
        System.out.println("Input (hex): " +
            new String(Hex.encode(input)));
        System.out.println("Output (hex): " +
            new String(Hex.encode(digest)));
    }
}

You will see this output:
Input (hex): 0001020304
Output (hex): d05374dc381d9b52806446a71c8e79b1

To focus on the MD5 function of bouncycastle library, the input is set to fix value.


1 comment:

  1. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. my programming lab

    ReplyDelete