在我的代码中,我需要使用各种算法(包括CRC32)来散列文件。由于我还在Digest
系列中使用其他加密散列函数,因此我认为为它们全部保持一致的界面会很好。Digest :: CRC32与Zlib
为了记录,我找到了digest-crc
,这是一个完全符合我想要的宝石。事情是,Zlib
是标准库的一部分,并且有一个我想要重用的CRC32的工作实现。此外,它是用C语言编写的,所以它应该提供比digest-crc
更好的性能,这是一个纯粹的ruby实现。
实施Digest::CRC32
实际上是在第一次看很简单:
%w(digest zlib).each { |f| require f }
class Digest::CRC32 < Digest::Class
include Digest::Instance
def update(str)
@crc32 = Zlib.crc32(str, @crc32)
end
def initialize; reset; end
def reset; @crc32 = 0; end
def finish; @crc32.to_s; end
end
一切看起来正确的:
crc32 = File.open('Rakefile') { |f| Zlib.crc32 f.read }
digest = Digest::CRC32.file('Rakefile').digest!.to_i
crc32 == digest
=> true
不幸的是,不是一切正常:
Digest::CRC32.file('Rakefile').hexdigest!
=> "313635393830353832"
# What I actually expected was:
Digest::CRC32.file('Rakefile').digest!.to_i.to_s(16)
=> "9e4a9a6"
hexdigest
基本上返回Digest.hexencode(digest)
,which works with the value of the digest at the byte level。我不确定这个函数是如何工作的,所以我想知道是否可以用Zlib.crc32
返回的整数来实现这个功能。
什么Ruby平台是你的工作吗? – 2potatocakes 2011-12-21 21:33:15
@ 2potatocakes,C Ruby 1.9.3。 – 2011-12-21 22:00:02