Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

2.35 Calculating the SHA-256 Hash of a String

The Digest::SHA256 class produces a 256-bit hash or message digest of a string of arbitrary length. This hashing function is one-way, and does not allow for the discovery of the original message from the digest. There are also MD5, SHA384, and SHA512 classes inside Digest for each of those algorithms.

The most commonly used class method is hexdigest, but there are also digest and base64digest. They all accept a string containing the message and return the digest as a string, as shown here:

require 'digest'
Digest::SHA256.hexdigest("foo")[0..20]    # "2c26b46b68f"
Digest::SHA256.base64digest("foo")[0..20] # "LCa0a2j/xo/"
Digest::SHA256.digest("foo")[0..5]        # ",&\xB4kh\xFF"

Although the digest method provides a 64-byte string containing the 512-bit digest, the hexdigest method is actually the most useful. It provides the digest as an ASCII string of 64 hex characters representing the 64 bytes.

Instances and the update method allow the hash to be built incrementally, perhaps because the data is coming from a streaming source:

secret = Digest::SHA256.new
source.each { |chunk| secret.update(chunk) }

Repeated calls are equivalent to a single call with concatenated arguments:

# These two statements...
cryptic.update(" and more data.")

# ...are equivalent to this one.
cryptic.update("Data... and more data.")

cryptic.hexdigest[0..20] # "50605ba0a90"
  • + Share This
  • 🔖 Save To Your Account