Sha256 Hashes in Elixir

Here’s the translation of the Go SHA256 hashes example to Elixir, formatted in Markdown suitable 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 Elixir.

defmodule SHA256Example do
  def main do
    s = "sha256 this string"

    # Here we start with a new hash.
    hash = :crypto.hash_init(:sha256)

    # Update expects binaries. If you have a string `s`,
    # use String.to_charlist(s) to coerce it to a charlist.
    hash = :crypto.hash_update(hash, String.to_charlist(s))

    # This gets the finalized hash result as a binary.
    bs = :crypto.hash_final(hash)

    IO.puts(s)
    IO.puts(Base.encode16(bs, case: :lower))
  end
end

SHA256Example.main()

Elixir uses the :crypto module from Erlang to perform cryptographic operations. The process is slightly different from Go, but achieves the same result.

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

$ elixir sha256_hashes.exs
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 :sha512 instead of :sha256 in the :crypto.hash_init/1 function.

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