javaclojurebase64urlencode

How to get Base64-encoded data without padding?


I'm very new to Clojure. I don't have any experience with Java and its library functions. I wrote a function in clojure which returns Base64-encoded data using java.util.Base64/getUrlEncoder. My code looks like this:

user> (import java.util.Base64)
java.util.Base64
user> (let [encoder (Base64/getUrlEncoder)]
        (String. (.encode encoder (.getBytes "Hello StackOverflow"))))
"SGVsbG8gU3RhY2tPdmVyZmxvdw=="

As you can see, the output contains padding: two equals signs at the end. I don't want that padding.

I see that Java's Base64.Encoder class has a 'withoutPadding()' method for this purpose, but I can't figure out how to use it in Clojure. I tried something like this:

user> (let [encoder (Base64/getUrlEncoder))]
        (doto (java.util.Base64/Encoder (.withoutPadding (String. (.encode encoder (.getBytes "Hello StackOverflow"))))))

but it didn't work. How can I do this?


Solution

  • You have to call withoutPadding on the Encoder itself:

    user> (import java.util.Base64)
    java.util.Base64
    user> (let [encoder (Base64/getUrlEncoder)]
            (String. (.encode encoder (.getBytes "Hello StackOverflow"))))
    "SGVsbG8gU3RhY2tPdmVyZmxvdw=="
    user> (let [encoder (.withoutPadding (Base64/getUrlEncoder))]
            (String. (.encode encoder (.getBytes "Hello StackOverflow"))))
    "SGVsbG8gU3RhY2tPdmVyZmxvdw"