24

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

pistacchio
  • 56,889
  • 107
  • 278
  • 420

6 Answers6

46

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)))
nlloyd
  • 1,966
  • 2
  • 15
  • 18
  • 1
    Note, if you want the string to be [URL safe](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html#getUrlEncoder--) use (Base64/getUrlEncoder) – KendallB Oct 27 '21 at 22:14
20

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"))
Brian Marick
  • 1,330
  • 1
  • 11
  • 12
12

You can use encode function and pass array of bytes:

(encode (.getBytes "Hello world!"))
Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43
3

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

(encode "hello" :base64 {:url-safe? true})
ruseel
  • 1,578
  • 2
  • 21
  • 41
3

For those trying (as I was) to turn images into data URIs (for embedding images in HTML):

(defn data-uri
  [imagepath]
  (str
   "data:image/"
   (second
    (re-find #"\.(.*$)" imagepath))
   ";base64,"
   (.encodeToString
    (java.util.Base64/getEncoder)
    (org.apache.commons.io.FileUtils/readFileToByteArray
     (clojure.java.io/file filepath)))))
Adam Lee
  • 1,784
  • 1
  • 11
  • 15
1

Possible duplicate of Clojure equivalent of python's base64 encode and decode

The Tupelo library has Clojure wrappers around the base Java Base64 and Base64Url functionality. A look at the unit tests show the code in action:

(ns tst.tupelo.base64
  (:require [tupelo.base64 :as b64] ))

code-str    (b64/encode-str  orig)
result      (b64/decode-str  code-str) ]
(is (= orig result))

where the input & output values are plain strings (there is also a variant for byte arrays).

The API docs are here.

Community
  • 1
  • 1
Alan Thompson
  • 29,276
  • 6
  • 41
  • 48