001/** 002 * 003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. 004 * 005 * This library is free software; you can redistribute it and/or 006 * modify it under the terms of the GNU Lesser General Public 007 * License as published by the Free Software Foundation; either 008 * version 2.1 of the License, or (at your option) any later version. 009 * 010 * This library is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013 * Lesser General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public 016 * License along with this library. If not, see <http://www.gnu.org/licenses/>. 017 * 018 **/ 019package lucee.commons.digest; 020import java.io.InputStream; 021import java.security.MessageDigest; 022 023import lucee.commons.io.IOUtil; 024import lucee.commons.io.res.Resource; 025 026public class MD5Checksum { 027 028 public static byte[] createChecksum(Resource res) throws Exception { 029 InputStream is = res.getInputStream(); 030 try{ 031 byte[] buffer = new byte[1024]; 032 MessageDigest complete = MessageDigest.getInstance("MD5"); 033 int numRead; 034 do { 035 numRead = is.read(buffer); 036 if (numRead > 0) { 037 complete.update(buffer, 0, numRead); 038 } 039 } 040 while (numRead != -1); 041 042 return complete.digest(); 043 } 044 finally { 045 IOUtil.closeEL(is); 046 } 047 048 049 } 050 051 // see this How-to for a faster way to convert 052 // a byte array to a HEX string 053 public static String getMD5Checksum(Resource res) throws Exception { 054 byte[] b = createChecksum(res); 055 String result = ""; 056 for (int i=0; i < b.length; i++) { 057 result += 058 Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ); 059 } 060 return result; 061 } 062}