Thursday, August 15, 2013

JAVA: Get MD5 Hash On String

The following demonstrates how to perform MD5 hash on string. For it to run, you will need to import these 2 packages.
  • java.security.MessageDigest
  • javax.xml.bind.annotation.adapters.HexBinaryAdapter
public static void main(String[] args) {
    try {
        String hash1 = computeMD5Hash1("hello world");
        String hash2 = computeMD5Hash2("hello world");
        System.out.println(hash1);
        System.out.println(hash2);
    } catch (Exception e) {
    }
}

//using HexBinaryAdapter to convert byte array to string
public static String computeMD5Hash1(String plainText) {
    String hash = "";
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        hash = (new HexBinaryAdapter()).marshal(md5.digest(plainText.getBytes()));
        hash = hash.toUpperCase();
    } catch (Exception e) {
        hash = "";
    }

    return hash;
}

//no library to convert byte array to string
public static String computeMD5Hash2(String plainText) {
    String hash = "";
    try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] bb = md5.digest(plainText.getBytes());
        for (byte b : bb)
            hash += String.format("%02X", b & 0xff);
    } catch (Exception e) {
        hash = "";
    }

    return hash;
}

No comments:

Post a Comment

Do provide your constructive comment. I appreciate that.