如何在Clojure中生成固定长度的随机密码?

Nic*_*ick 8 clojure

是否有快速生成固定长度的随机密码?(例如,8位数,字母/数字/下划线)

run*_*xec 12

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"
Run Code Online (Sandbox Code Playgroud)


api*_*iga 5

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"
Run Code Online (Sandbox Code Playgroud)

这是 runexec 的答案的一个细微变化,您可以在其中看到如何选择您的随机字符串应该使用的字符。