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
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
(:import java.util.Base64) (defn encode [to-encode] (.encode (Base64/getEncoder) (.getBytes to-encode)))
(:import java.util.Base64) (defn encode [to-encode] (.encodeToString (Base64/getEncoder) (.getBytes to-encode)))
(:import java.util.Base64) (defn decode [to-decode] (String. (.decode (Base64/getDecoder) to-decode)))
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"))
You can use encode function and pass array of bytes:
(encode (.getBytes "Hello world!"))
ztellman/byte-transforms also support base64 encode/decode.
(encode "hello" :base64 {:url-safe? true})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With