Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 550
Robin Avatar asked Oct 15 '25 07:10

Robin


2 Answers

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"
like image 133
Garrett Rowe Avatar answered Oct 16 '25 19:10

Garrett Rowe


For JAVA 21, i used this code :

Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
like image 28
Zakariae BEN ALLAL Avatar answered Oct 16 '25 20:10

Zakariae BEN ALLAL