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