Base64 Encoding in Clojure

Clojure provides built-in support for base64 encoding/decoding.

(ns base64-encoding
  (:require [clojure.data.codec.base64 :as b64]))

(defn main []
  ;; Here's the string we'll encode/decode.
  (let [data "abc123!?$*&()'-=@~"
        
        ;; Clojure supports both standard and URL-compatible
        ;; base64. Here's how to encode using the standard
        ;; encoder. The encoder requires a byte array, so we
        ;; convert our string to that type.
        s-enc (String. (b64/encode (.getBytes data)))
        _ (println s-enc)
        
        ;; Decoding may return an error, which you can handle
        ;; if you don't already know the input to be
        ;; well-formed.
        s-dec (String. (b64/decode (.getBytes s-enc)))
        _ (println s-dec)
        _ (println)
        
        ;; This encodes/decodes using a URL-compatible base64
        ;; format.
        u-enc (String. (b64/encode (.getBytes data) true))
        _ (println u-enc)
        u-dec (String. (b64/decode (.getBytes u-enc) true))]
    (println u-dec)))

(main)

To use this code, you’ll need to add the org.clojure/data.codec dependency to your project. You can do this by adding [org.clojure/data.codec "0.1.1"] to your project.clj file or the equivalent in your build tool of choice.

The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.

To run the program:

$ clj -M base64-encoding.clj
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

In Clojure, we use the clojure.data.codec.base64 library for base64 encoding and decoding. The encode and decode functions work with byte arrays, so we need to convert our strings to and from byte arrays.

The URL-safe version is achieved by passing true as a second argument to the encode and decode functions.

Note that error handling in Clojure is typically done using the try/catch mechanism, which we’ve omitted here for brevity. In a production environment, you’d want to handle potential exceptions from the decoding process.