Last active
January 2, 2025 15:31
-
-
Save snorremd/43c49649d2d844ee1e646fee67c141bb to your computer and use it in GitHub Desktop.
Passphrase in babashka using /dev/urandom and /usr/share/dict/words
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
#!/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!)) |
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
Updated to use a single filter expression for the word length. Thanks @kthu.