forked from yogsototh/clj-jwt
-
Notifications
You must be signed in to change notification settings - Fork 3
/
base64.clj
65 lines (55 loc) · 1.58 KB
/
base64.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
(ns clj-jwt.base64
(:require [clojure.data.codec.base64 :as base64]
[clojure.string :as str])
(:import [java.io ByteArrayInputStream ByteArrayOutputStream]))
(defprotocol ByteArrayInput (input-stream [this]))
(extend-type String
ByteArrayInput
(input-stream [src] (ByteArrayInputStream. (.getBytes src "UTF-8"))))
(extend-type (Class/forName "[B")
ByteArrayInput
(input-stream [src] (ByteArrayInputStream. src)))
;; Encoder
(defn encode
^bytes
[x]
(with-open [^ByteArrayInputStream in (input-stream x)
out (ByteArrayOutputStream.)]
(base64/encoding-transfer in out)
(.toByteArray out)))
(defn encode-str
[x & {:keys [^String charset] :or {charset "UTF-8"}}]
(String. (encode x) charset))
;; Decoder
(defn decode
^bytes
[x]
(with-open [^ByteArrayInputStream in (input-stream x)
out (ByteArrayOutputStream.)]
(base64/decoding-transfer in out)
(.toByteArray out)))
(defn decode-str
[x & {:keys [^String charset] :or {charset "UTF-8"}}]
(String. (decode x) charset))
;; URL-Safe Encoder
(defn url-safe-encode-str
[x]
(-> (encode-str x)
(str/replace #"\s" "")
(str/replace "=" "")
(str/replace "+" "-")
(str/replace "/" "_")))
;; URL-Safe Decoder
(defn url-safe-decode
^bytes
[^String s]
(-> (case (-> s .length (mod 4) long)
2 (str s "==")
3 (str s "=")
s)
(str/replace "-" "+")
(str/replace "_" "/")
decode))
(defn url-safe-decode-str
[^String s & {:keys [^String charset] :or {charset "UTF-8"}}]
(String. (url-safe-decode s) charset))