Skip to content

Instantly share code, notes, and snippets.

@snorremd
Last active June 19, 2020 18:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snorremd/43c49649d2d844ee1e646fee67c141bb to your computer and use it in GitHub Desktop.
Save snorremd/43c49649d2d844ee1e646fee67c141bb to your computer and use it in GitHub Desktop.
Passphrase in babashka using /dev/urandom and /usr/share/dict/words
#!/usr/bin/env bb
(defn random-bytes
[n]
(with-open [in (io/input-stream (io/file "/dev/urandom"))]
(let [buf (byte-array n)]
(.read in buf)
buf)))
(defn random-number
[n]
(let [factor (/ n (+ Integer/MAX_VALUE 1))]
(-> (random-bytes 4)
byte-array
java.math.BigInteger.
(as-> rand-int
(+ (* factor rand-int) 0))
int
(as-> num
(max num (- num))))))
(def word-list (->> "/usr/share/dict/words"
io/reader
line-seq
(filter #(> 10 (count %) 4))
(map str/lower-case)))
(def word-count (count word-list))
(defn passphrase!
[]
(->> (fn [] (nth word-list (random-number word-count)))
(repeatedly 5)
(str/join " ")))
(println (passphrase!))
@snorremd
Copy link
Author

Updated to use a single filter expression for the word length. Thanks @kthu.

@snorremd
Copy link
Author

Don't bind the read operation of the input stream in read-bytes to the _ symbol. Simply evaluate this side-effecting thing inside the let-expression's body.

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