Sha256 Hashes in Haskell
Here’s the translation of the SHA256 Hashes example from Go to Haskell:
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 Haskell.
Haskell implements several hash functions in the cryptonite
library, which we’re using here.
In this example, we start by importing the necessary modules: Crypto.Hash.SHA256
for the SHA256 algorithm, Data.ByteString.Char8
for working with ByteStrings, and Data.ByteString.Base16
for hexadecimal encoding.
We define our input string s
. Then, we use SHA256.hash
to compute the hash of our input string. Note that we need to convert our string to a ByteString
using BS.pack
.
The hash
function returns a ByteString
representing the raw bytes of the hash. To get a human-readable hexadecimal representation, we use Base16.encode
.
Finally, we print both the original string and the hexadecimal representation of its SHA256 hash.
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 import Crypto.Hash.SHA512
and use SHA512.hash
.
Note that if you need cryptographically secure hashes, you should carefully research hash strength!
To use this code, you’ll need to install the cryptonite
and base16-bytestring
packages. You can do this using Cabal or Stack:
or
Remember to add these dependencies to your project’s .cabal
or package.yaml
file if you’re using a Haskell project structure.