Thursday, 28 April 2011

How to create a checksum of a file in ruby?

Ruby Digest class does support many hashing algorithm. For example  sha1, sha2,sha256, md5 etc etc.
Md5 is most commonly used and it's known to be less secure than sha1.
Recently sha1 has been decoded by someone.
so, i prefer to use SHA2. :D



require "digest"
 Digest::SHA2.hexdigest("Your String")
 => "0544ecabc489156b6343d8d98e282d751462379ac30698c5224b5c3814d8d818"

To generate  a checksum of a file, instead  of putting your custom string as an argument to hexdigest method , just squirt the content of a file.

Digest::SHA2.hexdigest( File.read("/path/to/my/file.txt") );
OR
Digest::SHA2.file(myFile).hexdigest
 => "fa5880ac744f3c05c649a864739530ac387c8c8b0231a7d008c27f0f6a2753c7" 

where myFile can be  File.new("/path/to/file.txt") or simply a path to that file like "/path/to/file.txt".


No comments:

Post a Comment