Created
July 22, 2020 18:22
-
-
Save joshkh/99718bfd4cd95cd48cda8533f162ffbf to your computer and use it in GitHub Desktop.
cloudfront / s3 signature
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns signit | |
(:require [buddy.core.dsa :as dsa] | |
[buddy.core.codecs.base64 :as b64] | |
[clojure.string :as str]) | |
(:import [java.security Signature])) | |
(defn access-policy | |
"Create a stringified JSON policy to grant access to a URL until a given Epoch time" | |
[url exp] | |
(str "{\"Statement\":[{\"Resource\":\"" | |
url | |
"\",\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":" | |
exp | |
"}}}]}")) | |
(defn replace-valid-chars | |
"Replace unsafe URL query string characters with safe ones" | |
[s] | |
(str/replace s #"\+|=|/" (fn [m] (get {"+" "-" "=" "_" "/" "~"} m)))) | |
(defn sign [url exp private-key] | |
(-> (access-policy url exp) | |
(dsa/sign {:key private-key :alg #(Signature/getInstance "SHA1withRSA")}) | |
b64/encode | |
String. | |
replace-valid-chars)) | |
(defn sign-url [url exp private-key-id private-key] | |
(str | |
url | |
"?Expires=" exp | |
"&Key-Pair-Id=" private-key-id | |
"&Signature=" (sign url exp private-key))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment