Skip to content Skip to sidebar Skip to footer

Clojure Equivalent Of Python's Base64 Encode And Decode

I have this python code snippet and need help with a clojure equivalent. user_id = row.get('user_id') if user_id: user_id_bytes = base64.urlsafe_b64decode(user_id) creation

Solution 1:

You can use clojure's java compatibility to leverage the java.util.Base64 class.

user> (import java.util.Base64)
java.util.Base64

user> ;; encode a message(let [message "Hello World!"
           message-bytes (.getBytes message) 
           encoder (Base64/getUrlEncoder)]
       (.encodeToString encoder message-bytes)) 
"SGVsbG8gV29ybGQh"

user> ;; Decode a message(let [encoded-message "SGVsbG8gV29ybGQh"
            decoder (Base64/getUrlDecoder)]
        (String. (.decode decoder encoded-message)))
"Hello World!"

Solution 2:

The Tupelo library has Clojure wrappers around the 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.

Post a Comment for "Clojure Equivalent Of Python's Base64 Encode And Decode"