Skip to content

Instantly share code, notes, and snippets.

@jcromartie
Created October 28, 2009 21:55
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 jcromartie/220900 to your computer and use it in GitHub Desktop.
Save jcromartie/220900 to your computer and use it in GitHub Desktop.
(import 'java.security.MessageDigest)
(defn bytes-str
"Does what it says on the tin"
[byte-array]
(apply str (map #(format "%02x" (bit-and % 0xff)) byte-array)))
(defn sha-hash
"Returns the SHA hash of string s"
[s]
(bytes-str
(.digest
(doto (MessageDigest/getInstance "SHA-1") (.update (.getBytes s))))))
(defn salted-hash
[s]
(sha-hash (str "your salt here" s)))
(defn object-token
"Creates security token for a given object"
[x hash-fn]
(hash-fn (pr-str x)))
(def *token-key* :obj-hash)
(defn sign
"Returns an object with a verifiable signature"
[x]
(with-meta x (assoc ^x *token-key* (object-token x salted-hash))))
(defn auth
"Verifies the authenticity of a signed object"
[x]
(= (^x *token-key*) (object-token x salted-hash)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment