ryoakg
6/4/2016 - 3:34 AM

random-bytes.clj

;;; http://stackoverflow.com/questions/16748447/fastest-way-to-generate-random-strings

(require '[clojure.string :as str])

(defn get-key [chunk-size, key-length]
  (->> (repeatedly #(rand-nth "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
       (take key-length)
       (partition chunk-size)
       (interpose "-")
       flatten
       str/join))
(get-key 3 10) ;; => "Y9K-WOD-TUJ"

(defn get-name [key-length]
  (->> (repeatedly #(rand-nth "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"))
       (take key-length)
       str/join))
(get-name 6) ;; => "W52UM6"
;;; via https://gist.github.com/kurogelee/11258117
(defn ^bytes rand-bytes [n]
  (let [b (byte-array n)]
    (.. (SecureRandom.) (nextBytes b))
    b))

;;; Usage
(repeatedly 5 #(seq (rand-bytes 10)))
;; => ((114 -84 19 28 -8 -33 -6 37 -9 9) (82 89 53 -27 -106 -68 20 -69 -19 -52) (-85 16 118 55 84 -32 17 87 -54 50) (121 84 47 -10 38 66 75 -123 -28 -13) (75 89 -103 -1 -90 106 -61 95 -14 74))