Create MD5 hash in JSP

String plainText = "123456";
MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");
mdAlgorithm.update(plainText.getBytes());

byte[] digest = mdAlgorithm.digest();
StringBuffer hexString = new StringBuffer();

for (int i = 0; i < digest.length; i++) {
    plainText = Integer.toHexString(0xFF & digest[i]);

    if (plainText.length() < 2) {
        plainText = "0" + plainText;
    }

    hexString.append(plainText);
}

out.print(hexString.toString());
Published May 19, 2004 · Updated September 17, 2005
Categorized as Java
Short URL: https://snook.ca/s/158

Conversation

9 Comments · RSS feed
flip said on September 27, 2005

IMHO a very nice solution, all the others I've seen so far involve pages of code or some obscure libraries. Thank You!

Viktor said on December 19, 2005

I have been looking for this a long time, thanks!

Fuzz said on February 20, 2006

great solution!
import java.security

gid said on June 01, 2006

Works like a charm, the solution I was using,

String md5 = new BigInteger( 1, md.digest() ).toString(16);

wanted to truncated leading 0's, this one doesn't.

said on August 30, 2006

I used your code but modified it so I can hash strings and other objects.


    public static String getHash(Object o)
    {
    	try
    	{
    		MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5");
    		ByteArrayOutputStream baos = new ByteArrayOutputStream();
    		ObjectOutputStream oos = new ObjectOutputStream(baos);
    		oos.writeObject(o);
    		mdAlgorithm.update(baos.toByteArray());

    		byte[] digest = mdAlgorithm.digest();
    		StringBuffer hexString = new StringBuffer();

    		for (int i = 0; i < digest.length; i++)
    		{
    			String x = Integer.toHexString(0xFF & digest[i]);
    			if (x.length() < 2) x = "0" + x;
    			hexString.append(x);
    		}
    		return(hexString.toString());
    	}
    	catch(NoSuchAlgorithmException e) { return(null); }
    	catch(IOException e) { return(null); }
    }
Patrick said on October 27, 2006

Thanks! This solution saves me some time ;)

d said on November 18, 2006

<script>
var i=0;
while (var<5)
{
documnet.write("Hello World!");
var=var+1;
}
</script>

Jon Cram said on December 06, 2006

Excellent example!

I'm just starting out building Java apps and need to add some authentication.

I decided upon storing user details in a plain text file (college project - simplest option - not allowed to use a DB) and wanted to shadow passwords. Now I can!

Brian said on February 19, 2007

nice job!!!

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.