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
上一篇: 查找算法-二分查找的几种变体
下一篇: 最长公共子序列问题
推荐阅读
-
php结合md5实现的加密解密方法,php结合md5加密解密_PHP教程
-
用PHP写的MD5加密函数
-
讲解Linux中校验文件的MD5码与SHA1码的命令使用
-
纯php实现DES以及TripleDES加密算法
-
PHP:使用Zend对源码加密、Zend Guard安装以及Zend Guard Run-time support mi_PHP教程
-
利用PHP脚本在Linux下用md5函数加密字符串的方法,linuxmd5
-
用PHP写的MD5加密函数_PHP
-
node.JS的crypto加密模块使用方法详解(MD5,AES,Hmac,Diffie-Hellman加密)
-
php mcrypt启用、加密以及解密的方法介绍
-
Java实现SHA1加密代码实例