How to Use the Ruby Digest Module

09/23/2021

Contents

In this article, you will learn how to use the Ruby Digest module.

Using the Digest module

The Ruby Digest module provides several hash functions that can be used to create message digests or checksums of data. These functions take an input string and produce a fixed-length output, which can be used to verify the integrity of the original data.

To use the Digest module, you first need to require it in your Ruby script:

require 'digest'

Once you have required the module, you can call one of the available hash functions. The most commonly used functions are MD5, SHA1, SHA256, and SHA512. Here’s an example of how to use the SHA256 function:

require 'digest'

input_string = "This is the string to hash"
hash = Digest::SHA256.hexdigest(input_string)

puts "Hash value: #{hash}"

In this example, we first require the Digest module. We then create an input string that we want to hash. We pass this string to the SHA256 function using the hexdigest method, which returns a hexadecimal string representation of the hash value. We store this hash value in the hash variable and print it to the console.

You can also use the Digest module to create checksums of files. To do this, you first need to read the contents of the file into a string and then pass that string to the desired hash function. Here’s an example:

require 'digest'

filename = "example.txt"
file_contents = File.read(filename)
hash = Digest::SHA256.hexdigest(file_contents)

puts "Hash value: #{hash}"

In this example, we read the contents of the file example.txt into the file_contents variable using the File.read method. We then pass this variable to the SHA256 function to create a hash value, which we store in the hash variable and print to the console.

You can also use other methods provided by the Digest module, such as hexdigest, digest, and base64digest, to generate hash values with different formats. Additionally, the Digest module provides other functions such as HMAC, which can be used to create keyed hash functions.