# # File:: md5.rb # Description:: MD5 digest utility class. # # Author:: David Muir # Date:: 15 September 2008 # #----------------------------------------------------------------------------- # Uses #----------------------------------------------------------------------------- require 'digest/md5' #----------------------------------------------------------------------------- # Implementation #----------------------------------------------------------------------------- module Pipeline module Util # # == Description # MD5 digest utility class. This class contains a few methods to ease # generating MD5 digest checksums for files either read in a single # chunk or read in specific sized chunks. # class MD5 CHUNK_128K = ( 128 * 1024 ) CHUNK_256K = ( 256 * 1024 ) CHUNK_512K = ( 512 * 1024 ) CHUNK_1M = ( 1 * 1024 * 1024 ) CHUNK_2M = ( 2 * 1024 * 1024 ) CHUNK_4M = ( 4 * 1024 * 1024 ) CHUNK_8M = ( 8 * 1024 * 1024 ) CHUNK_16M = ( 16 * 1024 * 1024 ) CHUNK_32M = ( 32 * 1024 * 1024 ) # # Return the MD5 digest string for a given file. # def MD5::digest( filename, chunk_size = CHUNK_4M, mode = 'rb' ) throw IOError.new( "File #{filename} does not exist, or is not readable." ) \ unless ( ::File::exists?( filename ) and ::File::readable?( filename ) ) MD5::md5( filename, chunk_size, mode ).digest() end # # Return the MD5 hexdigest string for a given file. # def MD5::hexdigest( filename, chunk_size = CHUNK_4M, mode = 'rb' ) throw IOError.new( "File #{filename} does not exist, or is not readable." ) \ unless ( ::File::exists?( filename ) and ::File::readable?( filename ) ) MD5::md5( filename, chunk_size, mode ).hexdigest() end # # Return the Digest::MD5 object for a given file with the MD5 checksum # pre-calculated. # def MD5::md5( filename, chunk_size = CHUNK_4M, mode = 'rb' ) throw IOError.new( "File #{filename} does not exist, or is not readable." ) \ unless ( ::File::exists?( filename ) and ::File::readable?( filename ) ) md5 = Digest::MD5.new() ::File.open( filename, mode ) do |fp| while ( not fp.eof ) do data = fp.read( chunk_size ) md5 << data end end md5 end end end # Util module end # Pipeline module # md5.rb