Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure base64 encoding

I want something as simple as "string" -> base64. With the older base64.encode-str it was easy (and sounded "more clojure", but the newer clojure.data.codec.base64 requires input and output streams and seems an ugly wrapper around Java way of doing things.

So, what is the way, having a string, to get a base64 encoded array? Thanks

like image 341
pistacchio Avatar asked Aug 06 '12 09:08

pistacchio


4 Answers

Four years later, but I think this is worth mentioning if you're at JDK 1.8 or greater. It just uses java.util.Base64

To Encode String -> Base64:

(:import java.util.Base64)  (defn encode [to-encode]   (.encode (Base64/getEncoder) (.getBytes to-encode))) 

To Encode String -> Base64 (String):

(:import java.util.Base64)  (defn encode [to-encode]   (.encodeToString (Base64/getEncoder) (.getBytes to-encode))) 

To Decode Base64 (byte[] or String) -> String:

(:import java.util.Base64)  (defn decode [to-decode]   (String. (.decode (Base64/getDecoder) to-decode))) 
like image 137
nlloyd Avatar answered Sep 30 '22 06:09

nlloyd


There's one more step needed for the other answer: converting the byte-array result of encode into a string. Here's what I do:

(:require [clojure.data.codec.base64 :as b64])  (defn string-to-base64-string [original]   (String. (b64/encode (.getBytes original)) "UTF-8")) 
like image 31
Brian Marick Avatar answered Sep 30 '22 08:09

Brian Marick


You can use encode function and pass array of bytes:

(encode (.getBytes "Hello world!"))
like image 41
Mikita Belahlazau Avatar answered Sep 30 '22 06:09

Mikita Belahlazau


ztellman/byte-transforms also support base64 encode/decode.

(encode "hello" :base64 {:url-safe? true})
like image 38
ruseel Avatar answered Sep 30 '22 08:09

ruseel