Sha256 Hashes in Elm

Here’s the translation of the SHA256 Hashes example from Go to Elm, formatted in Markdown suitable for Hugo:

Elm doesn’t have built-in cryptographic functions like SHA256. However, we can use a third-party package to achieve similar functionality. For this example, we’ll use the elm-crypto package.

First, you need to install the package:

elm install ktonon/elm-crypto

Now, let’s create our Elm program:

module Main exposing (main)

import Crypto.Hash as Hash
import Html exposing (Html, div, text)

main : Html msg
main =
    let
        s = "sha256 this string"
        hash = Hash.sha256 s
    in
    div []
        [ text s
        , text "\n"
        , text hash
        ]

This program does the following:

  1. We import the necessary modules: Crypto.Hash for SHA256 functionality and Html for rendering.

  2. In the main function, we define our string s that we want to hash.

  3. We use Hash.sha256 function from the elm-crypto package to compute the SHA256 hash of our string.

  4. We then render the original string and its hash using HTML.

To run this program, you would typically use the Elm reactor or compile it to HTML and JavaScript.

$ elm reactor

Then open a web browser and navigate to http://localhost:8000. Find your Elm file and click on it. You should see the original string and its SHA256 hash displayed.

Note that unlike the Go example, Elm’s Hash.sha256 function directly returns a hex-encoded string, so we don’t need to do any additional formatting.

Also, Elm is a functional language that runs in the browser, so concepts like writing to the console or creating binary executables don’t directly apply. Instead, Elm programs typically produce HTML that’s rendered in the browser.

Remember that if you need cryptographically secure hashes, you should carefully research hash strength and the security of the libraries you’re using, especially in a browser environment.