HOWTO: Use Java to Compute an md5sum of a String

| No TrackBacks
If you've ever needed to use Java to compute an md5sum of a String, you can find a convenient Java md5sum class here (JavaMD5Sum.java) ...
/**
 * Copyright (c) 2008 Mark S. Kolich
 * http://mark.koli.ch
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
*/

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaMD5Sum {
	
	public static final String MD5_ALGORITHM = "MD5";
	
	public static void main ( String [] args ) {
		try {
		   System.out.println( "string 1 = " + computeSum("string 1") );
		   System.out.println( "string 2 = " + computeSum("string 2") );
		   System.out.println( "string 3 = " + computeSum("string 3") );
		} catch (NoSuchAlgorithmException e) {
		   System.err.print( e.getStackTrace() );
		}
	}

	/**
	 * Uses Java to compute the MD5 sum of a given input String.
	 * @param input
	 * @return
	 */
	public static final String computeSum(String input)
		throws NoSuchAlgorithmException {

		if (input == null) {
		   throw new IllegalArgumentException("Input cannot be null!");
		}

		StringBuffer sbuf = new StringBuffer();
		MessageDigest md = MessageDigest.getInstance(MD5_ALGORITHM);
		byte [] raw = md.digest(input.getBytes());
		
		for (int i = 0; i < raw.length; i++) {
			int c = (int) raw[i];
			if (c < 0) {
				c = (Math.abs(c) - 1) ^ 255;
			}
			String block = toHex(c >>> 4) + toHex(c & 15);
			sbuf.append(block);
		}
		
		return sbuf.toString();
		
	}

	private static final String toHex(int s) {
		if (s < 10) {
		   return new StringBuffer().
append((char)('0' + s)).
toString(); } else { return new StringBuffer().
append((char)('A' + (s - 10))).
toString(); } } }

Did You Find this Helpful?

Did you find this post helpful, or at least, interesting?

  

Send Mark a Direct Message

If you'd like to send me a direct message, please do so below. However, I do not publicly post comments or messages submitted directly to me. So, if you're going to try to SPAM me, or my blog, you're pretty much wasting your time.

400 characters remaining

Error

About Mark

A Silicon Valley native, Mark Kolich is a full-time Software Engineer, a casual entrepreneur, and a consultant for hire. A web technologies expert, his current focus is on building powerful and robust cloud-driven web-applications using Java, PHP, Perl, AJAX, DHTML, CSS, and JavaScript. His favorite programming languages are PHP, Java and JavaScript. He uses Linux, enjoys biking to work, loves building great software, and always writes elegant, readable, and maintainable code.

No TrackBacks

No trackbacks attached to this entry.

Twitter (@markkolich)

Translate

About this Entry

This page contains a single entry by Mark Kolich published on November 25, 2008 8:50 PM.

America's in a "Credit Crisis"; Yet I Still Receive Multiple Credit Card Offers Each Day was the previous entry in this blog.

Use Java to Watch Your Axis Network Camera (Java Axis Viewer) is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.