0

I need a hash algorithm while using Ruby. In my situation I'm comparing the contents of the file. I was using MD5, but it examines the filename as well (or seems to anyway). Is there an algorithm that I can easily implement or will I have to write one from scratch?

3 Answers 3

2

Use FileUtils.compare_file.

require 'fileutils'
FileUtils.compare_file('somefile', 'somefile')  #=> true
Sign up to request clarification or add additional context in comments.

1 Comment

Looking at the implementation of this, it compares the two file streams block wise and stops as soon the blocks don't match. Interesting method, didn't know it before.
2

I'm not sure why do you think it compares filename?

require "digest"
Digest::MD5.hexdigest(File.read('file1'))
=> "60b725f10c9c85c70d97880dfe8191b3"
Digest::MD5.hexdigest(File.read('file2'))
=> "60b725f10c9c85c70d97880dfe8191b3"

What did you do to get different checksums?

4 Comments

Really? I used FileUtils.cp and it gave me different sums. It really doesn't make sense to me either.
@avatarmonkeykirby How do you mean cp? compare_file returns true on those files as well. Maybe files in question are different (whitespace etc...)
@avatarmonkeykirby: you should paste that code in the question.
I used FileUtils.cp to copy the file and THEN compared the sums with MD5. This is probably a problem with my computer.
0

This is similar to the answer above but uses SHA256, as MD5 was broken by rainbow tables if I recall correctly

require 'digest'

puts "Hello!"
puts Digest::SHA256.hexdigest 'message'
puts Digest::SHA256.hexdigest 'message2'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.