Question

I wrote this little test script in Ruby (on MacOS):

#!/usr/bin/ruby
require 'digest/sha2'

def calc_sha(file)
  # calc hash
  hash = Digest::SHA2.new
  File.open(file, 'r') do |fh|
    fh.each_line do |l|
      hash << l
    end
  end

  hash.to_s
end

puts calc_sha('dont-panic.jpeg')
puts '40075d8441ab6a9abeceb7039552704320f471667b8f9ac3c18b9b5b0a1fee7e'
puts calc_sha('dont-panic.jpeg') ==  '40075d8441ab6a9abeceb7039552704320f471667b8f9ac3c18b9b5b0a1fee7e'

Which outputs (on MacOS):

~/shatest $ ./sha.rb 
40075d8441ab6a9abeceb7039552704320f471667b8f9ac3c18b9b5b0a1fee7e
40075d8441ab6a9abeceb7039552704320f471667b8f9ac3c18b9b5b0a1fee7e
true

Then I run the exact same Script in Windows XP:

F:\shatest>ruby sha.rb
9c787b71392551238b24915c888dbd44f4ff465c8e8aadca7af3bb6aaf66a3ca
40075d8441ab6a9abeceb7039552704320f471667b8f9ac3c18b9b5b0a1fee7e
false

Can anyone tell me whats the Problem here?

Was it helpful?

Solution

You're opening a JPEG (i.e. a binary file) and then reading every line of text from it. Don't do that. Any time you treat binary data as text, you're just asking for odd behaviour.

I don't know much about Ruby at all, but I'd generally expect to open the file, and repeatedly read chunks of binary data from it, updating the hash with that. Don't do anything which talks about "lines" or uses text at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top