Skip to content

Instantly share code, notes, and snippets.

@uvtc
Last active December 25, 2015 01:39
Show Gist options
  • Save uvtc/6896279 to your computer and use it in GitHub Desktop.
Save uvtc/6896279 to your computer and use it in GitHub Desktop.
decoding base64-encoded text
(require '[clojure.data.codec.base64 :as base64])
;;---------------------------------------------------
;; From <http://en.wikipedia.org/wiki/Base64>
(def input "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=")
(let [output (base64/decode input)]
(println output))
;; That fails, I think because base64/decode wants a byte array. Ok. Let's
;; instead try:
(let [output (base64/decode (.getBytes input))]
(println output))
;; That prints out what appears to be a byte array. How
;; can I turn that into a string?
;; This gets me closer:
(let [output (String. (base64/decode (.getBytes input)))]
(println output))
;; But yields a mix of correct text and gibberish in my terminal window.
;; Note, the base64-encoded text is not all ascii.
@sparkhom
Copy link

sparkhom commented Oct 9, 2013

Your input has newlines, which need to be taken out before you do a base64 decode. Either make the input one line, or do a clojure.string/replace on the text to clean up the newlines.

@uvtc
Copy link
Author

uvtc commented Oct 11, 2013

Thanks, sparkhom. Seems like base64/decode should accomodate that...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment