MD5 and SHA256 Digests in Ruby
Due to the nature of what I do at work, and also due to my getting burned by corrupted Linux iso downloads, I've been very interested in putting together a quick script to calculate MD5 and SHA256 digests/checksums. At work I use SHA256 checksums to ensure the files I send to collaborators are not corrupted during the process, and that the results we produce are true originals. That's basically the same thing with downloaded software -- you run MD5 or SHA256 on the file and check the checksums to ensure the files were not corrupted during the download process.
Thus, I created a short script in Ruby that prints out the MD5 and SHA256 digests/checksums on the command line. I wrapped this script in a windows batch file to make it even easier to use. And b/c I'm an uber-geek, I also set the path to the batch file in my windows PATH environment variable.
Being a good agile programmer I tested everything using Unit Testing. I zipped everything up and you can download it from my site here. The code I'm distributing in the zip file is licensed under GPL v3.
To run the batch file from the command line:
D:\>md5_sha256 .\ruby_code\security_hash\test.txt SHA256 Digest: b31be10c867258146b4b10409fa6ffd46e5e196b7a4f9d11c0c354903cafdaa1 MD5 Digest: 3e09efe7694c40db6ad990f9d7d8e786
And here's the ruby code:
require 'digest' class SecurityHash attr_reader :md5_digest, :sha256_digest def initialize(file_name) #file_name = ARGV[0] @sha256_digest = Digest::SHA256.file(file_name).hexdigest @md5_digest = Digest::MD5.file(file_name).hexdigest puts "SHA256 Digest: #{@sha256_digest}" puts "MD5 Digest: #{@md5_digest}" end end security_hash = SecurityHash.new ARGV[0] |
The unit test is rather simple:
require "test/unit" require 'security_hash' class SecurityHashTest < Test::Unit::TestCase def test_md5 security_hash = SecurityHash.new "test.txt" assert_equal '3e09efe7694c40db6ad990f9d7d8e786', security_hash.md5_digest end def test_sha256 security_hash = SecurityHash.new "test.txt" assert_equal 'b31be10c867258146b4b10409fa6ffd46e5e196b7a4f9d11c0c354903cafdaa1', security_hash.sha256_digest end end |