MD5s in Java

Charlton Rose gnucash-devel@sharkysoft.com
Tue, 15 May 2001 16:12:27 -0700 (PDT)


I've heard on this mailing list crazy things ranging from "You can't
compute MD5s in Java" to "Yes you can; so-and-so has a library you can
use."

The truth is, Java has built in support for MD5s and no extra toolkits or
libraries are necessary.

To demonstrate, here is a little snippet from one of my own Java
components (lava.io.IoToolbox) that uses Java's built-in MD5 support.



/**********************************************************************
Computes a message digest from a stream.

<p><b>Details:</b>  <code>computeStreamDigest</code> computes a message digest for the supplied input stream, closes the stream, and then returns the digest.</p>

<p>The digest name must be one of the standard digest names provided in the Java Security API.</p>

@param is the input stream
@param algo the digest algorithm
@return the digest
@exception IOException if an I/O error occurs

@since 1999.10.21
**********************************************************************/

public static byte[] computeStreamDigest (InputStream is, String algo)
	throws IOException, NoSuchAlgorithmException
{
	try
	{
		MessageDigest md = MessageDigest.getInstance (algo);
		if (! (is instanceof BufferedInputStream))
			is = new BufferedInputStream (is);
		byte[] buff = new byte [1024];
		while (true)
		{
			int n = is . read (buff);
			if (n < 0)
				break;
			md . update (buff, 0, n);
		}
		return md . digest ();
	}
	finally
	{
		// (lava.io.IoCloser, not a standard Java class)
		IoCloser.close (is);
	}
}



Hope this is helpful to whomever needs MD5s in Java.

-----

Charlton Rose
Software Consultant
Sharkysoft

web: http://sharkysoft.com/   (business)
web: http://charltonrose.com/ (personal)
im : AIM / homesharky