Sunday, March 7, 2010

Java 01

Over the next few entries, I'm going to show you how to do a simple integrity check. Implementation will be done in Java, so we will need to learn how to do hashing, how to transmit a message through TCP, and how to implement a basic integrity check that involves a PSK.
So now we're going to talk a little bit about hash. What is a hash? A hash is a complex function, usually recursive, that takes a variable length input and outputs a fixed length output. A small change in the input (such as a change in a few bits) can result in drastically different results, due to an avalanche effect.

For example, the MD5 hash of "The quick brown fox jumps over the lazy dog" gives 9e107d9d372bb6826bd81d3542a419d6. If we add a fullstop at the back, the hash would become e4d909c290d0fb1ca068ffaddf22cbd0.

The two most popular hashing functions are MD5 and SHA-1. One may believe that MD5 is the stronger among the two due to its omnipresence, but SHA-1 is actually more secure. MD5 gives a 128-bit output while SHA-1 returns 160-bit. MD5 is typically used for file integrity checks while SHA-1 is more popular in situations where security is key, such as in IPSec.

Today we'll learn how to implement SHA-1 in Java. There are already packages that does the complex algorithms for us, so all we'll have to do is to implement the classes provided.

First we'll import the MessageDigest class:
import java.security.MessageDigest;

We then instantiate it:
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");

Notice that I put "SHA-1" as the parameter for the getInstance method. To change the hashing algorithm, simply change that parameter. The list can be found here.

After that, we can start adding the input we wish to hash. To do this, use:

message in this case is a String containing the message to be hashed. You can use various other data-types, as long as you cast them into byte. You can concatenate more input if you wish; simply call the update() method multiple times.

When you're ready, call the digest() method to retrieve the output:
byte[] messageDigestDigest = messageDigest.digest();

To show it in String form, concatenate it with a for-loop:
for (int i=0;i<messageDigestDigest.length;i++)

No comments :

Post a Comment