Calculating a MD5, SHA1, SHA256, SHA384, SHA512 Hash in Java

Hi, today I will show you with examples how to evaluate Hashes in Java programming language. I hope this information comes in useful for many people.

Java which is my favorite programming language because of sheer simplicity, vastness and ease with which you can customize and extend existing libraries to suit your needs.

/**
 * The getHash method returns the hash of the message
 *
 * @param message The message to be hashed
 * @param algorithm The hashing algorithm to be used,
 *                  Possible values are MD2, MD5, SHA-1, SHA-256, SHA-384, SHA-512
 *
 * @return The hash of the message
 *
 * @author Dhruva Sagar
 */
public String getHash(String message, String algorithm) {
  try {
    byte[] buffer = message.getBytes();
    MessageDigest md = MessageDigest.getInstance(algorithm);
    md.update(buffer);
    byte[] digest = md.digest();
    String hexValue = null;
    for(int i = 0 ; i < digest.length ; i++) {
      int b = digest[i] & 0xff;
        if (Integer.toHexString(b).length() == 1) hex = hex + "0";
          hex  = hex + Integer.toHexString(b);
        }
      return hex;
    } catch(NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return null;
}
comments powered by Disqus