欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MD5以及SHA1加密

程序员文章站 2022-03-14 23:16:46
...
require 'digest/md5'
require 'digest/sha1'

$BUFLEN = 1024

class Hasher
	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

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

def usage
	puts "Usage: Hasher.rb [-SHA1|-MD5] filename"
end

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

if (ARGV.length == 2)
	hashcomp = Hasher.new(ARGV[0], ARGV[1])
	result(ARGV[1], hashcomp.hashname, hashcomp.hashsum)
	
elsif (ARGV.length == 1)
	hashcomp = Hasher.new("-MD5", ARGV[0])
	result(ARGV[0], hashcomp.hashname, hashcomp.hashsum)
else
	usage
end

 

新建一个txt文件,内容为javaeye

 

输入如下命令进行MD5加密:

 

ruby test.rb -MD5 test.txt

 

结果如下所示:

 

D:\test.txt ==> MD5: 9f06e9b2a48f887dde4490a3b0cb56a6

 

接着进行SHA1加密:

 

ruby test.rb -SHA1 D:\test.txt

 

结果如下所示:

 

D:\test.txt ==> SHA1: 8f4ed04be86a2816aafee7336ff15b6a9c3085c9

 

相关标签: Ruby