Base64 Encoding in Clojure
Clojure provides built-in support for base64 encoding/decoding.
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:
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.