在我的代码中,我需要使用各种算法(包括 CRC32)对文件进行哈希处理。由于我还在使用该Digest
系列中的其他加密哈希函数,我认为为它们维护一个一致的接口会很好。
作为记录,我确实找到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)
,它与字节级别的摘要值一起使用。我不确定该函数是如何工作的,所以我想知道是否可以仅使用从Zlib.crc32
.