Last active
August 18, 2018 01:56
-
-
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
This file contains hidden or 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
(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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
don't use SHA1 these days though