Computing a hexidecimal hash for a string is a very common function used in web development. It’s so common that most scripting languages provide a MD5 function that does just that. e.g. MD5(“Your favorite string goes here”);
Well I’ve found myself needing to generate hashes in Java apps a couple of times, and have found myself very disappointed in the amount of code required to perform what seems to me like a very mundane task. Simply put, it’s a pain in the butt.
So, I wrote a simple Java class with a single static method to do just that. To use it just type:
String myHash = DigestUtil.computeHexDigest(DigestUtil.ALGORITHM_MD5, "your favorite string goes here");
And that’s that. Well, it’ll never be as simple as but this beats the pants off doing it manually.
So, without further adieu, here’s the code ripe for copying-and-pasting into your app. Sorry for the formatting, WordPress is giving me trouble.
–BEGIN CODE SNIPPET–
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class DigestUtil
{
/**
* Constant representing the MD2 hash algorithm
*/
public static String ALGORITHM_MD2 = “MD2″;
/**
* Constant representing the MD5 hash algorithm
*/
public static String ALGORITHM_MD5 = “MD5″;
/**
* Constant representing the SHA-1 hash algorithm
*/
public static String ALGORITHM_SHA1 = “SHA-1″;
/**
* Constant representing the SHA-256 hash algorithm
*/
public static String ALGORITHM_SHA256 = “SHA-256″;
/**
* Constant representing the SHA-384 hash algorithm
*/
public static String ALGORITHM_SHA384 = “SHA-384″;
/**
* Constant representing the SHA-512 hash algorithm
*/
public static String ALGORITHM_SHA512 = “SHA-512″;
/**
*
* Computes the hexadecimal hash key for <em>input</em> using given <em>algorithm</em>
*
* @param algorithm
* @param input
* @return
* @throws NoSuchAlgorithmException
*
*/
public static String computeHexDigest(String algorithm, String input)
throws NoSuchAlgorithmException
{
byte [] inputBytes = input.getBytes();
MessageDigest md = MessageDigest.getInstance(algorithm);
byte [] digest = md.digest(inputBytes);
BigInteger bigNumber = new BigInteger(1, digest);
String hash = bigNumber.toString(16);
if ( hash.length() < 64 )
{
StringBuffer buf = new StringBuffer();
for ( int i = 1; i < 64 – hash.length(); i++ )
{
buf.append(“0″);
}
hash = buf.toString() + hash;
}
return hash;
}
}
–END CODE SNIPPET–
Recent Comments