Skip to content

Instantly share code, notes, and snippets.

@rufoa
Last active August 18, 2018 01:56
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 rufoa/f7901bfda28ce0ea49a8 to your computer and use it in GitHub Desktop.
Save rufoa/f7901bfda28ce0ea49a8 to your computer and use it in GitHub Desktop.
the correct way to use SecureRandom in clojure. automatically reseeds every ttl ms
(defn- reseeding-prng [ttl]
(let [state (atom {})]
(fn []
(let [now (.getTime (java.util.Date.))]
(when (> (- now (:last-seeded @state 0)) ttl)
(let [new-generator (java.security.SecureRandom/getInstance "SHA1PRNG" "SUN")]
(.nextBytes new-generator (byte-array 0))
(swap! state assoc :last-seeded now :generator new-generator)))
(:generator @state)))))
(def ^:private prng (reseeding-prng (* 60 60 1000)))
(defn- random-id []
(.toString (BigInteger. 160 (prng)) 36))
@rufoa
Copy link
Author

rufoa commented Jun 4, 2015

don't use SHA1 these days though

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