본문 바로가기

Programming/Ruby, Python

Ruby - File 의 sha1sum, md5sum 구하기

아래의 코드는 Linux 명령어 중에서 sha1sum, md5sum 명령어와 같은 기능을 하는 코드입니다.

# Simple Hash Code Calculator
# Returns SHA1 and MD5 hash sum for any given file

require 'digest/md5'
require 'digest/sha1'

# buffer size 4 kbytes
BUFFER_SIZE = 4096

class Hasher
# method = "sha1" or "md5"
# filepath = Full filepath
def initialize(method, filepath)
if (method.upcase == "-SHA1")
@hashfunc = Digest::SHA1.new
@hashname = "SHA1"
else
@hashfunc = Digest::MD5.new
@hashname = "MD5"
end
@fullfilename = filepath
end

def hashname
@hashname
end

# Compute hash code
def hashsum
open(@fullfilename, "r") do |io|
puts "Reading "+@fullfilename
counter = 0
while (!io.eof)
readBuf = io.readpartial(BUFFER_SIZE)
putc '.' if ((counter+=1) % 3 == 0)
@hashfunc.update(readBuf)
end
end
return @hashfunc.hexdigest
end
end

def usage
puts "Usage: hash.rb [-sha1|-md5] filename"
end

def print_result(filename, method, sum)
puts "\n" + filename + " ==> "+ method + ": " + sum
end

#Program starts
if(ARGV.length < 1)
usage
elsif (ARGV.length == 2)
hashcomp = Hasher.new(ARGV[0], ARGV[1])
print_result(ARGV[1], hashcomp.hashname, hashcomp.hashsum)
elsif (ARGV.length == 1)
hashcomp = Hasher.new("-sha1", ARGV[0])
print_result(ARGV[0], hashcomp.hashname, hashcomp.hashsum)
end