Sha256 Hashes in Crystal

Here’s the translation of the SHA256 Hashes example from Go to Crystal, 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 Crystal.

require "openssl"
require "digest"

# Crystal implements several hash functions in the
# Digest and OpenSSL modules.

s = "sha256 this string"

# Here we start with a new hash.
digest = OpenSSL::Digest.new("SHA256")

# We can directly update the digest with a string.
digest.update(s)

# This gets the finalized hash result as a byte slice.
bs = digest.final

puts s
puts bs.hexstring

Crystal uses the OpenSSL::Digest class to create hash functions. We specify “SHA256” as the algorithm when creating the digest object.

The update method is used to add data to the hash. In Crystal, we can directly pass a string to this method, unlike in some other languages where you might need to convert the string to bytes first.

The final method computes the hash and returns it as a byte slice. We then use the hexstring method to convert the byte slice to a hexadecimal string for printing.

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

$ crystal sha256_hashes.cr
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 would use OpenSSL::Digest.new("SHA512").

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