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.

import qualified Crypto.Hash.SHA256 as SHA256
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Base16 as Base16

main :: IO ()
main = do
    let s = "sha256 this string"
    
    -- Create a SHA256 hash of the input string
    let hash = SHA256.hash $ BS.pack s
    
    -- Convert the hash to a hexadecimal string
    let hexHash = Base16.encode hash
    
    putStrLn s
    putStrLn $ BS.unpack hexHash

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.

$ runhaskell sha256-hashes.hs
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0d63eb8c17a0b0b

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:

$ cabal install cryptonite base16-bytestring

or

$ stack install cryptonite base16-bytestring

Remember to add these dependencies to your project’s .cabal or package.yaml file if you’re using a Haskell project structure.