Sha256 Hashes in Clojure

Here’s the translation of the SHA256 Hashes example from Go to Clojure, 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 Clojure.

(ns sha256-hashes
  (:import (java.security MessageDigest)
           (javax.xml.bind DatatypeConverter)))

(defn sha256
  [s]
  (let [algorithm (MessageDigest/getInstance "SHA-256")
        raw (.digest algorithm (.getBytes s))]
    (DatatypeConverter/printHexBinary raw)))

(defn -main
  []
  (let [s "sha256 this string"]
    (println s)
    (println (sha256 s))))

In Clojure, we use Java’s built-in cryptography libraries to compute the SHA256 hash. The sha256 function takes a string, converts it to bytes, computes the hash, and then converts the result to a hexadecimal string.

To run the program:

$ clj -m sha256-hashes
sha256 this string
1AF1DFA857BF1D8814FE1AF8983C18080019922E557F15A8A0678C2836AE91B8

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

You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you would use “SHA-512” as the algorithm name in MessageDigest/getInstance.

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