Sha256 Hashes in OCaml

Here’s the translation of the SHA256 Hashes example from Go to OCaml:

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

open Digestif

let () =
  let s = "sha256 this string" in

  (* Here we create a new hash *)
  let h = SHA256.digest_string s in

  (* Convert the digest to a hexadecimal string *)
  let bs = SHA256.to_hex h in

  Printf.printf "%s\n" s;
  Printf.printf "%s\n" bs

OCaml implements several hash functions in the Digestif library, which we’re using here.

In this example, we start by creating a SHA256 digest of our input string using SHA256.digest_string. This function handles the entire process of creating the hash and finalizing it.

We then convert the digest to a hexadecimal string representation using SHA256.to_hex.

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

To run the program, you would typically compile it with OCaml and then execute the resulting binary:

$ ocamlopt -o sha256_hashes sha256_hashes.ml
$ ./sha256_hashes
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.digest_string and SHA512.to_hex.

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