sha1_file
-
There are generally two different ways in Ruby to generate a cryptographic hash of a file. The first and easiest way is to use
File.readto read the entire file contents into memory. We can then use the sameSHA1.hexdigestmethod on the contents to generate the hash.PHP
print sha1_file("my_file.jpg"); // => 5de1a26c24b0d176c6cafd11bf1f03017bcc767b
Ruby
require "digest" print Digest::SHA1.hexdigest(File.read("my_file.jpg")) # => 5de1a26c24b0d176c6cafd11bf1f03017bcc767b
The code above works for many cases but for larger files, there’s a risk of consuming large amounts of memory. For these cases, we can initialize a new digest with
Digest::SHA1.newand then read the file in smaller chunks, incrementally building the digest withSHA1#update.Ruby
require "digest" digest = Digest::SHA1.new File.open("my_file.jpg", "r") do |f| digest.update f.read(8192) until f.eof end print digest.hexdigest # => 5de1a26c24b0d176c6cafd11bf1f03017bcc767b
see also
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

