base64-encode-decode-utf8
Clojure
(import '[java.nio.charset StandardCharsets]
'[java.util Base64])
(defn b64-encode
"Encodes a string (UTF-8) or byte array as a Base64 string."
[v]
(let [bs (if (string? v) (.getBytes ^String v StandardCharsets/UTF_8) v)]
(.encodeToString (Base64/getEncoder) ^bytes bs)))
(defn b64-decode
"Decodes Base64 text to a UTF-8 string, wrapping bad input in ex-info."
[s]
(try
(String. (.decode (Base64/getDecoder) ^String s) StandardCharsets/UTF_8)
(catch IllegalArgumentException e
(throw (ex-info (str "Invalid Base64: " (ex-message e)) {:input s} e)))))