Sha256 Hashes in PureScript

Here’s the translation of the SHA256 hashes example from Go to PureScript:

module Main where

import Prelude

import Crypto.Hash (sha256)
import Data.ArrayBuffer.Types (Uint8Array)
import Data.TextEncoder (encodeUtf8)
import Effect (Effect)
import Effect.Console (log, logShow)
import Node.Buffer as Buffer
import Node.Encoding (Encoding(..))

main :: Effect Unit
main = do
  let s = "sha256 this string"

  -- Convert the string to a Uint8Array
  buf <- Buffer.fromString s UTF8
  uint8Array <- Buffer.toUint8Array buf

  -- Compute the SHA256 hash
  let hash = sha256 uint8Array

  -- Convert the hash to a hexadecimal string
  hexHash <- Buffer.toString Hex =<< Buffer.fromArrayBuffer hash

  log s
  log hexHash

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

PureScript implements several hash functions in the purescript-crypto package.

In this example, we start by importing the necessary modules, including Crypto.Hash for the SHA256 function, and various modules for working with strings, buffers, and arrays.

The main function is the entry point of our program. We define a string s that we want to hash.

To compute the hash, we first need to convert our string to a Uint8Array. We do this by creating a Buffer from the string using UTF-8 encoding, then converting that buffer to a Uint8Array.

We then use the sha256 function from the Crypto.Hash module to compute the hash of our Uint8Array.

The resulting hash is an ArrayBuffer. To display it in a human-readable format, we convert it back to a Buffer, then to a hexadecimal string.

Finally, we print both the original string and its hash.

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

$ spago run
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 the sha512 function from the same Crypto.Hash module.

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