Skip to content

Instantly share code, notes, and snippets.

@jhickner
Created April 14, 2012 07:00
Show Gist options
  • Select an option

  • Save jhickner/2382543 to your computer and use it in GitHub Desktop.

Select an option

Save jhickner/2382543 to your computer and use it in GitHub Desktop.
hmac
(ns oauth.digest
(:import (javax.crypto Mac)
(javax.crypto.spec SecretKeySpec)))
(defn hmac
"Calculate HMAC signature for given data."
[^String key ^String data]
(let [hmac-sha1 "HmacSHA1"
signing-key (SecretKeySpec. (.getBytes key) hmac-sha1)
mac (doto (Mac/getInstance hmac-sha1) (.init signing-key))]
(String. (org.apache.commons.codec.binary.Base64/encodeBase64
(.doFinal mac (.getBytes data)))
"UTF-8")))
(defn hmac-sha-256
[key-seq byte-seq]
(let [hmac-key (SecretKeySpec. (byte-array key-seq) "HmacSHA256")
hmac (doto (Mac/getInstance "HmacSHA256") (.init hmac-key))]
(.doFinal hmac (byte-array byte-seq))))
@spacegangster
Copy link

spacegangster commented Feb 3, 2020

if someone will need a PHP-like version – take this
Different algo and will output hex, instead of UTF-8 formatted string

(defn hmac
  "Calculate HMAC signature for given data."
  [^String key ^String data]
  (let [algo "HmacSHA256"
        signing-key (SecretKeySpec. (.getBytes key) algo)
        mac (doto (Mac/getInstance algo) (.init signing-key))]
    (format "%x" (BigInteger. (.doFinal mac (.getBytes data))))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment