Sha256 Hashes in Erlang

Here’s an idiomatic Erlang example demonstrating the concept of SHA256 hashes:

-module(sha256_hashes).
-export([main/0]).

main() ->
    % The string we want to hash
    String = "sha256 this string",

    % Compute the SHA256 hash
    Hash = crypto:hash(sha256, String),

    % Convert the hash to a hexadecimal string
    HexHash = binary:encode_hex(Hash),

    % Print the original string and its hash
    io:format("~s~n", [String]),
    io:format("~s~n", [HexHash]).

This Erlang program demonstrates how to compute SHA256 hashes. Let’s break it down:

  1. We define a module named sha256_hashes and export the main/0 function.

  2. In the main/0 function, we first define the string we want to hash.

  3. We use the crypto:hash/2 function to compute the SHA256 hash. The first argument specifies the hash algorithm (sha256), and the second is the input string.

  4. The resulting hash is a binary. We convert it to a hexadecimal string using binary:encode_hex/1.

  5. Finally, we print both the original string and its hash using io:format/2.

To run this program:

  1. Save the code in a file named sha256_hashes.erl.
  2. Open a terminal and navigate to the directory containing the file.
  3. Start the Erlang shell by typing erl.
  4. Compile the module:
1> c(sha256_hashes).
{ok,sha256_hashes}
  1. Run the main/0 function:
2> sha256_hashes:main().
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0d63597dca7d3bc
ok

This example demonstrates how to use Erlang’s built-in cryptographic functions to compute SHA256 hashes. The crypto module in Erlang provides various cryptographic functions, including different hash algorithms.

Note that in Erlang, we don’t need to explicitly create a hash object or write to it step by step. The crypto:hash/2 function handles the entire process in one call, which is more idiomatic for Erlang.

Remember that if you need cryptographically secure hashes for sensitive applications, you should carefully research hash strength and consult with security experts.