Jun 03

We can use an MD5 implementation of the MessageDigest class to calculate the MD5 sum of a file (or any array of bytes). Once we have that it is simply a matter of feeding the contents of the file to the digest and have it calculate the MD5 sum as shown in the following example.

// Get an MD5 implementation of MessageDigest

MessageDigest digest = MessageDigest.getInstance("MD5");

// Open file and read contents

InputStream is = new FileInputStream(file);				
byte[] buffer = new byte[8192];
int read = 0;
while( (read = is.read(buffer)) >= 0)
{
   // pass data read from file to digest for processing

   digest.update(buffer, 0, read);
}		
is.close();

// Get the MD5 sum

byte[] md5sum = digest.digest();

// (Optionally) convert the MD5 byte array to a hex string

String md5sumHex = new BigInteger(1, md5sum).toString(16);

written by objects \\ tags: , , , ,

May 05

If you have a hex value as a string and you need the ASCII character that corresponds to that value then you need to parse your string to get its value. Once you have its value it is a simple cast to convert it to an ASCII character

eg. 4A (hex) -> 74 (dec) -> ‘J’

// First parse the hext String

int value = Integer.parseInt(hexString, 16);

// Then cast it to a char

char c = (char) value;

written by objects \\ tags: , ,

Apr 15

The BigDecimal class makes this really easy as it has a method toByteArray() that returns exactly what we need. Just need to create a BigDecimal and call the method.

   byte[] bytes = new BigInteger(hexString, 16).toByteArray();

written by objects \\ tags: , ,