Sha256 Hashes in Lisp

Here’s the translation of the SHA256 Hashes example from Go to Lisp, formatted in Markdown suitable for Hugo:

In Lisp, we can compute SHA256 hashes using the ironclad library. 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 Lisp.

(ql:quickload :ironclad)
(ql:quickload :babel)

(defun main ()
  (let ((s "sha256 this string"))
    ;; Here we create a new SHA256 digest
    (let ((digest (ironclad:make-digest :sha256)))
      ;; Update the digest with the bytes of the string
      (ironclad:update-digest digest (babel:string-to-octets s))
      
      ;; This gets the finalized hash result as a byte array
      (let ((result (ironclad:produce-digest digest)))
        ;; Print the original string and the hash
        (format t "~a~%" s)
        (format t "~(~{~2,'0x~}~)~%" (coerce result 'list))))))

(main)

In this Lisp version:

  1. We use the ironclad library for cryptographic functions and babel for string-to-byte conversion.

  2. We define a main function that demonstrates the SHA256 hashing process.

  3. We create a new SHA256 digest using ironclad:make-digest :sha256.

  4. The ironclad:update-digest function is used to feed the input string (converted to bytes) into the digest.

  5. We finalize the hash and get the result using ironclad:produce-digest.

  6. Finally, we print the original string and the hash in hexadecimal format.

To run the program, save it in a file (e.g., sha256-hashes.lisp) and use your Lisp interpreter. Make sure you have Quicklisp installed and the required libraries are available.

$ sbcl --load sha256-hashes.lisp
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 when creating the digest.

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