Is there a quick way to generate random password with fixed length? (for example, 8 digits, letter/number/underscore)
user> (defn fixed-length-password
([] (fixed-length-password 8))
([n]
(let [chars (map char (range 33 127))
password (take n (repeatedly #(rand-nth chars)))]
(reduce str password))))
#'user/fixed-length-password
user> (fixed-length-password 10)
;=> "N&L[yyLUI4"
user> (fixed-length-password 10)
;-> "8JSF-:?si."
user> (fixed-length-password 10)
;=> "EbKS~?*J*h"
user> (defn fixed-length-password
([] (fixed-length-password 8))
([n]
(let [chars-between #(map char (range (int %1) (inc (int %2))))
chars (concat (chars-between \0 \9)
(chars-between \a \z)
(chars-between \A \Z)
[\_])
password (take n (repeatedly #(rand-nth chars)))]
(reduce str password))))
#'user/fixed-length-password
user> (fixed-length-password 10)
;=> "Pfm0hwppMr"
user> (fixed-length-password 10)
;-> "n6lQoz_KGd"
user> (fixed-length-password 10)
;=> "vCkubQR75Z"
This is a slight change on runexec's answer, where you can see how to select what characters your random string should be using.
You may want to use the crypto-random
library. It is by the same author of Compojure
, and suited for cryptographic purposes.
Notice that it wraps Java libraries under the hood (java.security
and apache-commons
. Have a look at the code ! It's so tiny.
Specifically in your case you may be looking for the hex
function, so the solution would be : (crypto.random/hex size)
.
(defn rand-string [characters n]
(->> (fn [] (rand-nth characters))
repeatedly
(take n)
(apply str)))
It's not deterministic as-is because rand-nth has side-effects, but it should be enough for you to get started with.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With