I'm exploring some of Java's Cryptography Extension. I'm trying to create a function that lets me calculate a hash of some string (for storing passwords in a database, for example). Using various sources (forums.java.sun.com, google, etc.) I ended up with this. It seems to work ok, but I'd like someone else look over my code to see if I missed something.
I wrapped the code in a small application for your compiling/execution comfort.
Code:
/**
* Testing java message digesting.
*
* This class should be compiled using JDK 1.5 or higher
*/
import java.security.*;
class MessageDigestingTest
{
/* Supported Message Digest Algorithms in JDK.5, afaik:
*
* MD2
* MD5
* SHA-1
* SHA-256
* SHA-384
* SHA-512
*/
private static final String ALGORITHM = "SHA-512";
private static final char HEXCHAR[] = { '0','1','2','3','4','5','6','7', '8','9','a','b','c','d','e','f'};
public static void main(String[] args)
{
if (args.length < 1)
{
System.out.println("Usage: MessageDigestingTest toBeDigestedString");
}
else
{
System.out.println("Digesting using " + ALGORITHM + ": " + args[0]);
System.out.println(digest(ALGORITHM, args[0]));
}
}
private static String digest(String algorithm, String message)
{
/* StringBuilder is new in JDK1.5. It's a faster,
but thread-unsafe, version of StringBuffer. */
StringBuilder hexString = new StringBuilder();
try
{
byte[] pwdBytes = message.getBytes();
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(pwdBytes);
byte[] mesgdig = md.digest();
for (int i=0; i<mesgdig.length; i++)
{
int c = ((int) mesgdig[i]) & 0xff;
hexString.append(HEXCHAR[c >> 4 & 0xf]);
hexString.append(HEXCHAR[c & 0xf]);
}
}
catch (NoSuchAlgorithmException nsae)
{
System.err.printf("\nError while hashing password for logging.\nMessage: %s\n", nsae.getMessage());
}
return hexString.toString();
}
}