【发布时间】:2014-10-04 06:22:24
【问题描述】:
在我的代码中,我需要使用各种算法(包括 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)、which works with the value of the digest at the byte level。我不确定该函数是如何工作的,所以我想知道是否可以仅使用从 Zlib.crc32 返回的整数来实现这一点。
【问题讨论】:
-
你在哪个 ruby 平台上工作?