Sha256 Hashes in Racket

Here’s the translation of the SHA256 Hashes example from Go to Racket, with explanations in Markdown format suitable for Hugo:

#lang racket

(require openssl/sha2)
(require racket/format)

(define (main)
  (define s "sha256 this string")

  ; Here we start with a new hash.
  (define h (sha256-init))

  ; We update the hash with the bytes of our string.
  ; In Racket, strings are already sequences of bytes, so no conversion is needed.
  (sha256-update h s)

  ; This gets the finalized hash result as a byte string.
  (define bs (sha256-final h))

  (printf "~a\n" s)
  (printf "~a\n" (bytes->hex-string bs)))

(main)

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

Racket implements several hash functions in the openssl library. We’re using the sha256 functions from openssl/sha2.

In this example, we start by creating a new SHA256 hash object with sha256-init. We then update the hash with our input string using sha256-update. Unlike some other languages, Racket strings are already sequences of bytes, so we don’t need to explicitly convert the string to bytes.

After updating the hash with our input, we finalize it with sha256-final, which returns the hash as a byte string.

Finally, we print the original string and the computed hash. We use bytes->hex-string to convert the byte string to a hexadecimal representation for easy reading.

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

$ racket sha256-hashes.rkt
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0678c2836757115

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-init, sha512-update, and sha512-final functions from the same openssl/sha2 library.

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