Skip to content

Instantly share code, notes, and snippets.

@joshkh
Created July 22, 2020 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshkh/99718bfd4cd95cd48cda8533f162ffbf to your computer and use it in GitHub Desktop.
Save joshkh/99718bfd4cd95cd48cda8533f162ffbf to your computer and use it in GitHub Desktop.
cloudfront / s3 signature
(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