001 package railo.commons.digest; 002 import java.io.InputStream; 003 import java.security.MessageDigest; 004 005 import railo.commons.io.IOUtil; 006 import railo.commons.io.res.Resource; 007 008 public class MD5Checksum { 009 010 public static byte[] createChecksum(Resource res) throws Exception { 011 InputStream is = res.getInputStream(); 012 try{ 013 byte[] buffer = new byte[1024]; 014 MessageDigest complete = MessageDigest.getInstance("MD5"); 015 int numRead; 016 do { 017 numRead = is.read(buffer); 018 if (numRead > 0) { 019 complete.update(buffer, 0, numRead); 020 } 021 } 022 while (numRead != -1); 023 024 return complete.digest(); 025 } 026 finally { 027 IOUtil.closeEL(is); 028 } 029 030 031 } 032 033 // see this How-to for a faster way to convert 034 // a byte array to a HEX string 035 public static String getMD5Checksum(Resource res) throws Exception { 036 byte[] b = createChecksum(res); 037 String result = ""; 038 for (int i=0; i < b.length; i++) { 039 result += 040 Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ); 041 } 042 return result; 043 } 044 }