signature.clj 1.3 KB

123456789101112131415161718192021222324252627282930313233
  1. (ns imgproxy-test
  2. (:require
  3. [clojure.test :refer [deftest is]])
  4. (:import
  5. (java.util Base64)
  6. (javax.crypto Mac)
  7. (javax.crypto.spec SecretKeySpec)))
  8. (defn hex-string-to-byte-array
  9. [hex]
  10. (let [res (byte-array (/ (count hex) 2))]
  11. (dotimes [i (count res)]
  12. (aset res
  13. i
  14. (unchecked-byte (bit-or (bit-shift-left (Character/digit (nth hex (* i 2)) 16) 4)
  15. (Character/digit (nth hex (+ (* i 2) 1)) 16)))))
  16. res))
  17. (defn sign-path
  18. [key salt path]
  19. (let [mac (doto (Mac/getInstance "HmacSHA256") (.init (SecretKeySpec. key "HmacSHA256")))
  20. _ (.update mac salt)
  21. hash (.doFinal mac (.getBytes path "UTF-8"))
  22. encoded-hash (.. (Base64/getUrlEncoder) withoutPadding (encodeToString hash))]
  23. (str "/" encoded-hash path)))
  24. (deftest test-with-hmac-base64-img-proxy-test
  25. (is
  26. (=
  27. "/m3k5QADfcKPDj-SDI2AIogZbC3FlAXszuwhtWXYqavc/rs:fit:300:300/plain/http://img.example.com/pretty/image.jpg"
  28. (sign-path (hex-string-to-byte-array "943b421c9eb07c830af81030552c86009268de4e532ba2ee2eab8247c6da0881")
  29. (hex-string-to-byte-array "520f986b998545b4785e0defbc4f3c1203f22de2374a3d53cb7a7fe9fea309c5")
  30. "/rs:fit:300:300/plain/http://img.example.com/pretty/image.jpg"))))