Sha256 Hashes in Ruby

Here’s the translation of the SHA256 Hashes example from Go to Ruby, formatted in Markdown for Hugo:

SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in Ruby.

require 'digest'

# Define the string to be hashed
s = "sha256 this string"

# Create a new SHA256 hash object
h = Digest::SHA256.new

# Update the hash with the bytes of the string
h.update(s)

# Get the finalized hash result as a byte string
bs = h.digest

# Print the original string and the hash
puts s
puts bs.unpack1('H*')

Ruby implements several hash functions in the Digest module.

In this example, we start by requiring the digest library, which provides various cryptographic hash functions.

We create a new SHA256 hash object using Digest::SHA256.new.

The update method is used to add data to the hash. It automatically handles the conversion of the string to bytes.

To get the finalized hash result, we call the digest method, which returns the hash as a byte string.

Finally, we print the original string and the hash. The unpack1('H*') method is used to convert the byte string to a hexadecimal representation.

Running the program computes the hash and prints it in a human-readable hex format:

$ ruby sha256_hashes.rb
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you can use Digest::SHA512.new().

Note that if you need cryptographically secure hashes, you should carefully research hash strength!