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.

No comments:

Post a Comment