Created
May 9, 2021 19:38
-
-
Save vigevenoj/5b1668a5cae883b67a5d47ee4c5aad7a to your computer and use it in GitHub Desktop.
imgproxy url signing in clojure
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 doggallery.images-test | |
(:require [clojure.test :refer :all] | |
[buddy.core.codecs :as codecs]) | |
(:require [example.images :refer :all])) | |
(deftest imgproxy-url-generation | |
; this test replicates the java upstream | |
; https://github.com/imgproxy/imgproxy/blob/master/examples/signature.java | |
(testing "generate signed url for imgproxy" | |
(let [imgproxy-key (codecs/hex->bytes "943b421c9eb07c830af81030552c86009268de4e532ba2ee2eab8247c6da0881") | |
salt (codecs/hex->bytes "520f986b998545b4785e0defbc4f3c1203f22de2374a3d53cb7a7fe9fea309c5") | |
url "http://img.example.com/pretty/image.jpg" | |
resize "fill" | |
width 300 | |
height 300 | |
gravity "no" | |
enlarge 1 | |
extension "png" | |
url-with-hash (signed-imgproxy-url imgproxy-key salt url resize width height gravity enlarge extension)] | |
(is (= "/_PQ4ytCQMMp-1w1m_vP6g8Qb-Q7yF9mwghf6PddqxLw/fill/300/300/no/1/aHR0cDovL2ltZy5leGFtcGxlLmNvbS9wcmV0dHkvaW1hZ2UuanBn.png" url-with-hash))))) |
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 example.images | |
(:import java.util.Base64 | |
javax.crypto.Mac | |
javax.crypto.spec.SecretKeySpec)) | |
(defn signed-imgproxy-url | |
"Generate signed URL for imgproxy" | |
; adapted from https://github.com/imgproxy/imgproxy/blob/master/examples/signature.java | |
; this isn't very idiomatic clojure but once tests pass it can be fixed | |
[imgproxy-key salt url resize width height gravity enlarge extension] | |
(let [hmacsha256 "HmacSHA256" | |
encodedUrl (-> (Base64/getUrlEncoder) .withoutPadding (.encodeToString (.getBytes url))) | |
path (str "/" resize "/" width "/" height "/" gravity "/" enlarge "/" encodedUrl "." extension) | |
secret-key-spec (SecretKeySpec. imgproxy-key hmacsha256) | |
sha256hmac (Mac/getInstance hmacsha256) | |
hash (-> (Base64/getUrlEncoder) .withoutPadding (.encodeToString | |
(.doFinal | |
(doto sha256hmac | |
(.init secret-key-spec) | |
(.update salt)) | |
(.getBytes path))))] | |
(str "/" hash path))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment