[Crypto] Use enc/srng
This commit is contained in:
parent
649e140889
commit
f1c71b58d8
2 changed files with 10 additions and 24 deletions
|
|
@ -24,8 +24,8 @@
|
||||||
LazySeq IRecord ISeq IType]))
|
LazySeq IRecord ISeq IType]))
|
||||||
|
|
||||||
(if (vector? enc/encore-version)
|
(if (vector? enc/encore-version)
|
||||||
(enc/assert-min-encore-version [2 67 1])
|
(enc/assert-min-encore-version [2 121 0])
|
||||||
(enc/assert-min-encore-version 2.67))
|
(enc/assert-min-encore-version 2.121))
|
||||||
|
|
||||||
(comment
|
(comment
|
||||||
(set! *unchecked-math* :warn-on-boxed)
|
(set! *unchecked-math* :warn-on-boxed)
|
||||||
|
|
|
||||||
|
|
@ -11,28 +11,14 @@
|
||||||
;;;; Randomness
|
;;;; Randomness
|
||||||
|
|
||||||
(do
|
(do
|
||||||
(enc/compile-if (fn [] (java.security.SecureRandom/getInstanceStrong)) ; Java 8+, blocking
|
(defn rand-nth [coll] (nth coll (int (* (.nextDouble (enc/srng)) (count coll)))))
|
||||||
(def ^:private srng* (enc/thread-local-proxy (java.security.SecureRandom/getInstanceStrong)))
|
(defn rand-bytes ^bytes [size] (let [ba (byte-array size)] (.nextBytes (enc/srng) ba) ba))
|
||||||
(def ^:private srng* (enc/thread-local-proxy (java.security.SecureRandom/getInstance "SHA1SRNG"))))
|
(defn rand-double ^double [] (.nextDouble (enc/srng)))
|
||||||
|
(defn rand-gauss ^double [] (.nextGaussian (enc/srng)))
|
||||||
(defn srng
|
(defn rand-bool [] (.nextBoolean (enc/srng)))
|
||||||
"Favours security over performance. May block while waiting on system entropy!"
|
(defn rand-long
|
||||||
^java.security.SecureRandom []
|
(^long [ ] (.nextLong (enc/srng)))
|
||||||
(let [rng ^java.security.SecureRandom (.get ^ThreadLocal srng*)]
|
(^long [n] (long (* (long n) (.nextDouble (enc/srng)))))))
|
||||||
;; Occasionally supplement current seed for extra security.
|
|
||||||
;; Otherwise an attacker could *theoretically* observe large amounts of
|
|
||||||
;; srng output to determine initial seed, Ref. https://goo.gl/MPM91w
|
|
||||||
(when (< (.nextDouble rng) 2.44140625E-4) (.setSeed rng (.generateSeed rng 8)))
|
|
||||||
rng))
|
|
||||||
|
|
||||||
(defn rand-nth "Uses `srng`" [coll] (nth coll (int (* (.nextDouble (srng)) (count coll)))))
|
|
||||||
(defn rand-bytes "Uses `srng`" ^bytes [size] (let [ba (byte-array size)] (.nextBytes (srng) ba) ba))
|
|
||||||
(defn rand-double "Uses `srng`" ^double [] (.nextDouble (srng)))
|
|
||||||
(defn rand-gauss "Uses `srng`" ^double [] (.nextGaussian (srng)))
|
|
||||||
(defn rand-bool "Uses `srng`" [] (.nextBoolean (srng)))
|
|
||||||
(defn rand-long "Uses `srng`"
|
|
||||||
(^long [ ] (.nextLong (srng)))
|
|
||||||
(^long [n] (long (* (long n) (.nextDouble (srng)))))))
|
|
||||||
|
|
||||||
(comment
|
(comment
|
||||||
(seq (rand-bytes 16))
|
(seq (rand-bytes 16))
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue