Search code examples
rubybinary-datadigestbigint

Ruby: How can I write a digest to a file in binary format


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:

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?

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

Thank you in advance!


Solution

  • 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 = 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) }