Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random password with the fixed length in Clojure?

Tags:

clojure

Is there a quick way to generate random password with fixed length? (for example, 8 digits, letter/number/underscore)

like image 665
Nick Avatar asked Nov 21 '14 03:11

Nick


4 Answers

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"
like image 121
runexec Avatar answered Nov 10 '22 22:11

runexec


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.

like image 5
apiga Avatar answered Nov 10 '22 22:11

apiga


You may want to use the crypto-randomlibrary. It is by the same author of Compojure, and suited for cryptographic purposes.

Notice that it wraps Java libraries under the hood (java.securityand apache-commons. Have a look at the code ! It's so tiny.

Specifically in your case you may be looking for the hexfunction, so the solution would be : (crypto.random/hex size).

like image 3
nha Avatar answered Nov 10 '22 22:11

nha


(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.

like image 2
arrdem Avatar answered Nov 10 '22 23:11

arrdem