001package com.hfg.util.io; 002 003import java.io.InputStream; 004import java.io.ByteArrayInputStream; 005import java.security.MessageDigest; 006 007 008//------------------------------------------------------------------------------ 009/** 010 Calculates/validates MD5 checksums. 011 @author J. Alex Taylor, hairyfatguy.com 012 */ 013//------------------------------------------------------------------------------ 014// com.hfg XML/HTML Coding Library 015// 016// This library is free software; you can redistribute it and/or 017// modify it under the terms of the GNU Lesser General Public 018// License as published by the Free Software Foundation; either 019// version 2.1 of the License, or (at your option) any later version. 020// 021// This library is distributed in the hope that it will be useful, 022// but WITHOUT ANY WARRANTY; without even the implied warranty of 023// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 024// Lesser General Public License for more details. 025// 026// You should have received a copy of the GNU Lesser General Public 027// License along with this library; if not, write to the Free Software 028// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 029// 030// J. Alex Taylor, President, Founder, CEO, COO, CFO, OOPS hairyfatguy.com 031// jataylor@hairyfatguy.com 032//------------------------------------------------------------------------------ 033 034public class MD5Checksum 035{ 036 037 //########################################################################## 038 // PUBLIC METHODS 039 //########################################################################## 040 041 //-------------------------------------------------------------------------- 042 public static byte[] calculate(String inString) 043 { 044 return calculate(new ByteArrayInputStream(inString.getBytes())); 045 } 046 047 //-------------------------------------------------------------------------- 048 public static byte[] calculate(InputStream inStream) 049 { 050 MessageDigest md5 = null; 051 052 try 053 { 054 md5 = MessageDigest.getInstance("MD5"); 055 056 byte[] buffer = new byte[1024]; 057 int readSize; 058 059 while ((readSize = inStream.read(buffer)) > 0) 060 { 061 md5.update(buffer, 0, readSize); 062 } 063 064 inStream.close(); 065 } 066 catch (Exception e) 067 { 068 throw new RuntimeException("Problem calculating MD5 checksum!", e); 069 } 070 071 return md5.digest(); 072 } 073 074 //-------------------------------------------------------------------------- 075 public static boolean validate(String inString, byte[] inChecksum) 076 { 077 return validate(new ByteArrayInputStream(inString.getBytes()), inChecksum); 078 } 079 080 //-------------------------------------------------------------------------- 081 public static boolean validate(InputStream inStream, byte[] inChecksum) 082 { 083 String checksum1 = new String(calculate(inStream)); 084 085 return checksum1.equals(new String(inChecksum)); 086 } 087}