January 16, 2010

Java Bouncycastle SHA-1

Again, let’s try the next message digest algorithm SHA-1 using the bouncycastle library.
Recently, SHA-1 is quite popular in the CDMA industries since the algorithm is being used for generating the pseudo ESN/ pseudo UIMID.
And here is the code:


import java.security.Security;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.*;
import java.security.MessageDigest;

/**
*
* @author http://myprogramminglab.blogspot.com/
*/
public class sha1hash {
   public static void main(String[] args) {
       Security.addProvider(new BouncyCastleProvider());

      //this is the input;
      byte input[] = {0x30, 0x31, 0x32, 0x33, 0x34};

      try
      {
            //prepare the input
            MessageDigest hash =
               MessageDigest.getInstance("SHA-1", "BC");
            hash.update(input);

            //proceed ....
            byte[] digest = hash.digest();

            //show us the result
            System.out.println("input: " +
                   new String(Hex.encode(input)));
            System.out.println("result: " +
                   new String(Hex.encode(digest)));
      }
      catch (NoSuchAlgorithmException e)
      {
            System.err.println("No such algorithm");
            e.printStackTrace();
      }
      catch (NoSuchProviderException e)
      {
            System.err.println("No such provider");
            e.printStackTrace();
      }
   }
}


You will see this output:
input: 3031323334
result: 11904a4e8b77f6242e2d288705023adad00a9310

Let us discuss the code:

Security.addProvider(new BouncyCastleProvider());
is to install the bouncycastle provider during execution. You can also install it by configuring the Java Runtime which we won’t discuss in this topic

MessageDigest hash = MessageDigest.getInstance("SHA-1", "BC");
hash.update(input);

is to prepare the construct the MessageDigest class by calling getInstance. The first argument is the MessageDigest algorithm and the second argument is the provider. If you use bouncycastle library, then the provider is "BC" and since we use SHA-1 algorithm, the first argument is "SHA-1". The next line is to setup the input of the MessageDigest.

byte[] digest = hash.digest();
As you probably have guest, the digest function will digest the input and return the result.

System.out.println("input: " +
   new String(Hex.encode(input)));
System.out.println("result: " +
   new String(Hex.encode(digest)));

And the final step is to show the input and output to the screen.

No comments:

Post a Comment