Robin Robin - 5 months ago 25
Java Question

How to get encrypted data without padding?

I'm very new in clojure. I don't have any experience with java & it's library functions. I wrote a function in clojure which return base64 encrypted data using java.util.Base64/getUrlEncoder. My code look like:

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


The output contain padding as well(two equal sign at last). I want to remove padding from my output.
https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html#withoutPadding-- I know this is useful to solve my problem but I'm not able to figure out how to use withoutPadding() function 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 this is wrong. can anyone tell exact solution? Thanks.

Answer

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"