MD5 Hash of a String
Recently I search the forums for a way to get a MD5 Hash of a String. Unfortunantly, there was nothing here to help.
I did, however, find this site on the web:
http://users.rcn.com/danadler/javacom/MD5Hash.txt
The only thing is Dan Adler's code uses the older md5 class from sun. I have modified the code to use the MessageDigest class in the lastest version of java.security. With this class, you can get an all upper case 32 length hex string representation of the MD5 hash of a string...
String myhash = MD5Hash.hash(mystring);
So if you want to use a salt method to encrypt your passwords, or send clear text hashcodes in an insecure environment, this code will let you reliably create these hash code strings.
Dan Adler wrote the code, I have just modified it to add the latest MessageDigest stuff.
Regards,
aka elephantwalker
import java.security.*;
publicclass MD5Hashextends Object{
/**
* Private function to turn md5 result to 32 hex-digit string
*/
privatestatic String asHex (byte hash[]){
StringBuffer buf =new StringBuffer(hash.length * 2);
int i;
for (i = 0; i < hash.length; i++){
if (((int) hash[i] & 0xff) < 0x10)
buf.append("0");
buf.append(Long.toString((int) hash[i] & 0xff, 16));
}
return buf.toString().toUpperCase();
}
/**
* Take a string and return its md5 hash as a hex digit string
*/
publicstatic String hash(String arg)
{
return hash(arg.getBytes());
}
/**
* Non static version for VB
*/
public String doHash(String arg)
{
return hash(arg.getBytes());
}
/**
* Take a byte array and return its md5 hash as a hex digit string
*/
publicstatic String hash(byte barray[])
{
String restring ="";
try{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(barray);
byte[] result = md.digest();
restring = asHex(result);
}catch (NoSuchAlgorithmException nsa){}
return restring;
}
}

