I have required:
[clojure.data.codec.base64 :as b64]
I have defined a function:
(defn toHexString [bytes]
"Convert bytes to a String"
(apply str (map #(format "%x" %) bytes)))
I run this code to get a result in Clojure:
(toHexString (b64/decode (.getBytes "WR0frsVTzVg8QdA9l45/MuYZ3GUKGynDF7WaEYcjudI")))
I also run this code in PHP for comparison's sake (I am certain that the PHP result is correct):
echo bin2hex(base64_decode("WR0frsVTzVg8QdA9l45/MuYZ3GUKGynDF7WaEYcjudI"));
And I get these results for Clojure and PHP respectively:
591d1faec553cd583c41d03d978e7f32e619dc65a1b29c317b59a118723
591d1faec553cd583c41d03d978e7f32e619dc650a1b29c317b59a118723b9d2
Notice that the result is almost exactly the same. The only difference is the missing 0 in the middle and four missing characters at the end of the Clojure result.
I don't know what I am doing wrong here. Is the base64 decode function in Clojure broken? Or what am I doing wrong? Thanks in advance!
Your toHexString
needs to 0-pad for bytes that can be represented as a single hexadecimal number:
(defn to-hex-string [bytes] (apply str (map #(format "%02x" %) bytes)))
Your base64 input has length of 43, so it is either needs to be padded out to a multiple of 4 or decoded with an implementation that does not require padding. Looks like PHP accepts non-padded input and this Clojure does not (truncates). Pad with "=".
(to-hex-string (b64/decode (.getBytes "WR0frsVTzVg8QdA9l45/MuYZ3GUKGynDF7WaEYcjudI=")))
This now gives the expected output.