Showing posts with label Byte Array. Show all posts
Showing posts with label Byte Array. Show all posts

Friday, 10 August 2012

How to Digest (or Hash) data with MD5, SHA1, SHA256 in Java?

Java offers a functionality to compute/hash/digest messages. The available algorithms are: MD2, MD5, SHA-1, SHA-256, SHA-384 or SHA-512:
public static void main(String[] args)
        throws NoSuchAlgorithmException {

    byte[] ba = { 120, 35, 48, -33, -99, -10 };

    System.out.println("MD2     :"
        + Hex.encodeHexString(digest(ba, "MD2")));
 
    System.out.println("MD5     :"
        + Hex.encodeHexString(digest(ba, "MD5")));

    System.out.println("SHA-1   :"
        + Hex.encodeHexString(digest(ba, "SHA-1")));

    System.out.println("SHA-256 :"
        + Hex.encodeHexString(digest(ba, "SHA-256")));

    System.out.println("SHA-384 :"
        + Hex.encodeHexString(digest(ba, "SHA-384")));

    System.out.println("SHA-512 :"
        + Hex.encodeHexString(digest(ba, "SHA-512")));

}

public static byte[] digest(byte[] ba, String algorithm)
        throws NoSuchAlgorithmException {

    return MessageDigest.getInstance(algorithm).digest(ba);

}
We use the Hex class to convert byte arrays into hexadecimal strings. The generated output is:
MD2     :47493b5943a77cbd2d8a6d3907b3d215
MD5     :ce4f085c5bd8ecdc26a1b9ec94b8d081
SHA-1   :2a0d7f604439952d92b122fd872eee9bbb46b2d5
SHA-256 :de416f208796b60f0f2f1e17b3d0b1273580c29f71dac50fb8db46d1ed77c6c1
SHA-384 :439f5f0697c1dce75d4599e9256f1a4c11886846fc0cc342f5f8e3d70e5bb2890032c6dd359825ef267832266c6d09cd
SHA-512 :3b73aaec89f98bbb149380134036fcd6fdc4b18e59cad0bf6be704cd432de35c2dfb8f3901b8f1d6324bf53930b7f410b62db51beaab2e6959b98b3f53a28493

More Java tips & tricks here.

How to Convert a Byte Array Into an Hexadecimal String?

Trying to convert a byte array into an hexadecimal and back to the same byte array manually, can be tricky. The Hex class of the Apache Commons library offers a solution:
byte[] ba = { 4, 55, -27, 99, 42, 0, -1 };

String toHex = Hex.encodeHexString(ba);
byte[] retr = Hex.decodeHex(toHex.toCharArray());

System.out.println("Hexadecimal : " + toHex);
System.out.println("Expected    : " + Arrays.toString(ba));
System.out.println("Retrieved   : " + Arrays.toString(retr));

ba = new byte[0];
toHex = Hex.encodeHexString(ba);
retr = Hex.decodeHex(toHex.toCharArray());

System.out.println("Hexadecimal : " + toHex);
System.out.println("Expected    : " + Arrays.toString(ba));
System.out.println("Retrieved   : " + Arrays.toString(retr));
The generated output is:
Hexadecimal : 0437e5632a00ff
Expected    : [4, 55, -27, 99, 42, 0, -1]
Retrieved   : [4, 55, -27, 99, 42, 0, -1]

Hexadecimal :
Expected    : []
Retrieved   : []
More Java tips & tricks here.

How to Encode and Decode Data to Base64 in Java?

In order to encode a string (or a byte array) into Base64, and then decode it into its original state, one can use the following piece of code:
String s = "String to encode/decode in Base64 with DataTypeConverter";

String coded = DatatypeConverter.printBase64Binary(s.getBytes());
byte[] retr = DatatypeConverter.parseBase64Binary(coded);

System.out.println("Coded     : " + coded);
System.out.println("Expected  : " + s);
System.out.println("Retrieved : " + new String(retr));
System.out.println();
The generated output is:
Coded     : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHdpdGggRGF0YVR5cGVDb252ZXJ0ZXI=
Expected  : String to encode/decode in Base64 with DataTypeConverter
Retrieved : String to encode/decode in Base64 with DataTypeConverter

For input/output streams, one can use the following:
String s = "String to encode/decode in Base64 using streams";

ByteArrayOutputStream collect = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(collect);

b64os.write(s.getBytes());
b64os.close();

byte[] ba = collect.toByteArray();
String coded = new String(ba);

InputStream is = new ByteArrayInputStream(ba);
Base64InputStream b64is = new Base64InputStream(is);

byte[] retr = IOUtils.toByteArray(b64is);

System.out.println("Coded     : " + coded);
System.out.println("Expected  : " + s);
System.out.println("Retrieved : " + new String(retr));
The above uses an external library to convert the InputStream into a byte array. The generated output is:
Coded     : U3RyaW5nIHRvIGVuY29kZS9kZWNvZGUgaW4gQmFzZTY0IHVzaW5nIHN0cmVhbXM=
Expected  : String to encode/decode in Base64 using streams
Retrieved : String to encode/decode in Base64 using streams
The code examples are available from Github, in the Java-Core-Examples directory.

More Java tips & tricks here.

How to Convert an InputStream into a Byte Array in Java?

Sometimes, one has an input stream and would like to retrieve the content in a byte array. Unfortunately, Java does not deliver a suitable method for this. Fortunately, the Apache Commons library provides a solution:
byte[] ba = { -1, 2, -3, 4, 0, 66 };
InputStream bais = new ByteArrayInputStream(ba);

byte[] retr = IOUtils.toByteArray(bais);

System.out.println("Expected  : " + Arrays.toString(ba));
System.out.println("Retrieved : " + Arrays.toString(retr));
The generated output is:
Expected  : -1 2 -3 4 0 66 
Retrieved : -1 2 -3 4 0 66
This code example is also available from Github, in the Java-Core-Examples directory.

More Java tips & tricks here.