Ruby:如何以二进制格式将摘要写入文件

时间:2021-11-03 06:02:28

I need to store a Digest::SHA512 object to a file in binary format.
That seemed trivial, but whatever I try just write it as an hexadecimal string.
I was expecting the following code to work:

我需要将Digest :: SHA512对象以二进制格式存储到文件中。这似乎微不足道,但无论我尝试什么,只需将其写为十六进制字符串。我期待以下代码工作:

bindigest=digest.update(chall)
File.open('sha1.bin', 'wb') {|file| file.write(bindigest) }

but it does not: it convert to plain text.
A similar question seems unanswered: Can I serialize a ruby Digest::SHA1 instance object?

但它没有:它转换为纯文本。类似的问题似乎没有答案:我可以序列化ruby Digest :: SHA1实例对象吗?

Using unpack tools require translating a bigint into a binary string, which again is not trivial... Any suggestion?

使用解压缩工具需要将bigint转换为二进制字符串,这也不是一件容易的事......任何建议?

Thank you in advance!

先感谢您!

1 个解决方案

#1


The to_s method of Digest returns the hexadecimal encoding of the hash, so this is what you get by default when trying to output it (since Ruby will use to_s when writing). To get the raw binary, use digest:

Digest的to_s方法返回散列的十六进制编码,因此这是您在尝试输出时默认获得的(因为Ruby在写入时将使用to_s)。要获取原始二进制文件,请使用摘要:

digest = Digest::SHA512.new
digest.update(chall)
File.open('sha1.bin', 'wb') { |file| file.write(digest.digest) }

Alternatively you could use the class method version of digest if you’re not calculating the hash in chunks:

或者,如果您不计算块中的散列,则可以使用摘要的类方法版本:

digest = Digest::SHA512.digest(chall)
File.open('sha1.bin', 'wb') { |file| file.write(digest) }

#1


The to_s method of Digest returns the hexadecimal encoding of the hash, so this is what you get by default when trying to output it (since Ruby will use to_s when writing). To get the raw binary, use digest:

Digest的to_s方法返回散列的十六进制编码,因此这是您在尝试输出时默认获得的(因为Ruby在写入时将使用to_s)。要获取原始二进制文件,请使用摘要:

digest = Digest::SHA512.new
digest.update(chall)
File.open('sha1.bin', 'wb') { |file| file.write(digest.digest) }

Alternatively you could use the class method version of digest if you’re not calculating the hash in chunks:

或者,如果您不计算块中的散列,则可以使用摘要的类方法版本:

digest = Digest::SHA512.digest(chall)
File.open('sha1.bin', 'wb') { |file| file.write(digest) }