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.
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:
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!