Generate a random password or random string

From CodeCodex

Password generation code builds random passwords that match specific requirements.

Contents

Implementations

Bash

This is a simpler password generator. Note that the 'tr' strips out everything except characters in the ranges (alphanumeric, mixed case and underscores). This is a nice approach as piping to head means the minimum number of bytes required to generate a password of appropriate length are taken from /dev/urandom vs other methods which take more than you should need but still have a chance of not having obtained enough random data to generate a password of the required length. You can change the parameter to head to get passwords of any length.

</dev/urandom tr -dc A-Za-z0-9_ | head -c8

Alternatively you can do

cat /dev/urandom | base64 | head -c8

which wastes less entropy.

Common Lisp

You could use the Scheme version with only little modifications (most notably, (coerce foo 'string) instead of list->string), or use a somewhat more CL-ish iterative style:

(defun random-password (length)
  (let ((chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
    (coerce (loop repeat length collect (aref chars (random (length chars))))
            'string)))

An alternative is to take advantage of Common Lisp's string-streams and number printing support:

(defun random-password (length)
  (with-output-to-string (stream)
    (let ((*print-base* 36))
      (loop repeat length do (princ (random 36) stream)))))

Or in imperative style, side-effecting a pre-allocated string:

(defun random-password (length)
  (let ((chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
        (password (make-string length)))
    (dotimes (i length)
      (setf (aref password i) (aref chars (random (length chars)))))
    password))

Erlang

random_string(Len) ->
    Chrs = list_to_tuple("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"),
    ChrsSize = size(Chrs),
    F = fun(_, R) -> [element(random:uniform(ChrsSize), Chrs) | R] end,
    lists:foldl(F, "", lists:seq(1, Len)).

Groovy

def pool = ['a'..'z','A'..'Z',0..9,'_'].flatten()
Random rand = new Random(System.currentTimeMillis())

def passChars = (0..10).collect { pool[rand.nextInt(pool.size())] }
def password = passChars.join()

OR

def password = org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(length)

Java

    SecureRandom random = new SecureRandom();
    String str = new BigInteger(130, random).toString(32);

OR

public class RandomString {

          public static String randomstring(int lo, int hi){
                  int n = rand(lo, hi);
                  byte b[] = new byte[n];
                  for (int i = 0; i < n; i++)
                          b[i] = (byte)rand('a', 'z');
                  return new String(b, 0);
          }

          private static int rand(int lo, int hi){
                      java.util.Random rn = new java.util.Random();
                  int n = hi - lo + 1;
                  int i = rn.nextInt(n);
                  if (i < 0)
                          i = -i;
                  return lo + i;
          }

          public static String randomstring(){
                  return randomstring(5, 25);
          }

        /**
         * @param args
         */
        public static void main(String[] args) {
                System.out.println(randomstring());

        }

}

Applet

This applet will create a random password or random text.

import java.util.Random;

/**
 *
 * @author  hadstatj
 */
public class Passphrase extends java.applet.Applet
{
        Random  prng;

        String[]        vowels = {"a", "e", "i", "o", "u"};
        String[]        dipthg = {"ao", "ea", "eo", "ia", "io", "oa", "ua", "ue", "ui"};
        String[]        gencon = {"b", "c", "d", "f", "g", "j", "l", "m",
        "n", "p", "r", "s", "t", "v", "y", "z"};
        String[]    fincon = {"b", "c", "d", "f", "l", "m", "n", "p", "r",
        "s", "t"};
        String[]    dblcon = {"ch", "ll", "rr"};

        private static final byte mapNone = 0;
        private static final byte mapVowel = 1;
        private static final byte mapDipthg = 2;
        private static final byte mapGencon = 3;
        private static final byte mapFincon = 4;
        private static final byte mapDblcon = 5;

        byte[]  mapFirst =  {mapGencon, mapVowel};
        byte[]  mapAftVow = {mapGencon, mapGencon, mapGencon, mapGencon, mapFincon,
        mapNone, mapNone, mapNone, mapNone, mapDblcon};
        byte[]  mapAftGen = {mapVowel, mapVowel, mapVowel,
        mapVowel, mapVowel, mapVowel, mapDipthg};
        byte[]  mapAftDip = {mapGencon, mapFincon, mapNone, mapNone};

        String  GenWord()
        {
                int     i = 0, Dip = 0, Dbl = 0;
                int     minWdLen = 5;
                int     maxWdLen = minWdLen + prng.nextInt(4) + prng.nextInt(4) + prng.nextInt(4);
                byte[]  map = new byte[maxWdLen + 3];
                byte    nextType = mapFirst[prng.nextInt(mapFirst.length)];

                i = 0;
                map[i++] = nextType;

                while (i < minWdLen)
                {
                        byte    temp = nextType;

                        switch (nextType)
                        {
                                case mapVowel:
                                        nextType = mapAftVow[prng.nextInt(mapAftVow.length)];
                                        break;

                                case mapDipthg:
                                        Dip = 1;
                                        nextType = mapAftDip[prng.nextInt(mapAftDip.length)];
                                        break;

                                case mapFincon:
                                case mapGencon:
                                        nextType = mapAftGen[prng.nextInt(mapAftGen.length)];
                                        break;

                                case mapDblcon:
                                        Dbl = 1;
                                        nextType = mapVowel;
                                        break;
                        }

                        if (((Dip == 1) && (nextType == mapDipthg)) ||
                                        ((Dbl == 1) && (nextType == mapDblcon)) ||
                                        (nextType == mapNone))
                        {
                                nextType = temp;
                        }
                        else
                        {
                                map[i++] = nextType;
                        }
                }

                while ((i < maxWdLen) && (nextType != mapNone))
                {
                        byte    temp = nextType;

                        switch (nextType)
                        {
                                case mapVowel:
                                        nextType = mapAftVow[prng.nextInt(mapAftVow.length)];
                                        break;

                                case mapDipthg:
                                        Dip = 1;
                                        nextType = mapAftDip[prng.nextInt(mapAftDip.length)];
                                        break;

                                case mapGencon:
                                        nextType = mapAftGen[prng.nextInt(mapAftGen.length)];
                                        break;

                                case mapDblcon:
                                        Dbl = 1;
                                        nextType = mapVowel;
                                        break;

                                case mapFincon:
                                        nextType = mapNone;
                        }

                        if (((Dip == 1) && (nextType == mapDipthg)) ||
                                        ((Dbl == 1) && (nextType == mapDblcon))
                                        )
                        {
                                nextType = temp;
                        }
                        else
                        {
                                map[i++] = nextType;
                        }
                }

                while (nextType != mapNone)
                {
                        switch (nextType)
                        {
                                case mapVowel:
                                        nextType = mapNone;
                                        break;

                                case mapGencon:
                                        nextType = mapAftGen[prng.nextInt(mapAftGen.length)];
                                        break;

                                case mapFincon:
                                        nextType = mapNone;
                                        break;

                                case mapDipthg:
                                        nextType = mapNone;
                                        break;

                                case mapDblcon:
                                        nextType = mapVowel;
                                        break;
                        }

                        map[i++] = nextType;
                }

                StringBuffer    genWord = new StringBuffer();
                genWord.ensureCapacity(2 * i);

                for (i = 0; map[i] != mapNone; i++)
                {
                        switch (map[i])
                        {
                                case mapVowel:

                                        genWord.append(vowels[prng.nextInt(vowels.length)]);
                                        break;

                                case mapGencon:

                                        genWord.append(gencon[prng.nextInt(gencon.length)]);
                                        break;

                                case mapDipthg:

                                        genWord.append(dipthg[prng.nextInt(dipthg.length)]);
                                        break;

                                case mapDblcon:

                                        genWord.append(dblcon[prng.nextInt(dblcon.length)]);
                                        break;

                                case mapFincon:

                                        genWord.append(fincon[prng.nextInt(fincon.length)]);
                                        break;
                        }
                }

                return genWord.toString();
        }
        /** Initializes the applet Applet1 */
        public void init()
        {
                int i;

                prng = new Random();

                for (i = 0; i < 100000; i++) prng.nextBoolean();

                initComponents();
        }

        /** This method is called from within the init() method to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents()
    {
        DisplayArea = new java.awt.TextArea();
        MoreButton = new java.awt.Button();

        setLayout(new java.awt.BorderLayout());

        DisplayArea.setColumns(1);
        DisplayArea.setFont(new java.awt.Font("Monospaced", 0, 12));
        DisplayArea.setName("DisplayArea");
        add(DisplayArea, java.awt.BorderLayout.CENTER);

        MoreButton.setActionCommand("More");
        MoreButton.setLabel("More...");
        MoreButton.setName("More");
        MoreButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                MoreButtonActionPerformed(evt);
            }
        });

        add(MoreButton, java.awt.BorderLayout.SOUTH);

    }// </editor-fold>//GEN-END:initComponents

    private void MoreButtonActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_MoreButtonActionPerformed
    {//GEN-HEADEREND:event_MoreButtonActionPerformed
                DisplayArea.setText("");

                int i;

                for (i = 0; i < 8; i++)
                {
                        DisplayArea.append(GenWord());
                        DisplayArea.append("\r\n");
                }
    }//GEN-LAST:event_MoreButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.awt.TextArea DisplayArea;
    private java.awt.Button MoreButton;
    // End of variables declaration//GEN-END:variables

}

Source: John E. Hadstate

JavaScript

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

Original Source: StackOverflow

OCaml

# let gen_passwd length =
    let gen() = match Random.int(26+26+10) with
        n when n < 26 -> int_of_char 'a' + n
      | n when n < 26 + 26 -> int_of_char 'A' + n - 26
      | n -> int_of_char '0' + n - 26 - 26 in
    let gen _ = String.make 1 (char_of_int(gen())) in
    String.concat "" (Array.to_list (Array.init length gen));;

For example:

# gen_passwd 16;;
- : string = "6l2okhW7V1uq4wgu"

Alternativley:

 let gen_passwd =
   let alphanum =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" in
   let len = String.length alphanum in
   function n ->
     let str = String.create n in        
     for i=0 to pred n do
       str.[i] <- alphanum.[Random.int len]
     done;
     (str)            
 ;;

And here is how to allways generate the same random password for a given service:
(if you use it, change the private_seed for your own one)

 let init_random_with ~service_name =
   (* use your own private seed, not this one *)
   let private_seed = [| 366460539; 484630702; 945484951; 920863122; 660035151; 384227167 |] in
   let len = String.length service_name in
   let service_seed = Array.init len (fun i -> int_of_char service_name.[i]) in
   let seed_array = Array.append service_seed private_seed in
   Random.full_init seed_array
 ;;
 
 let passwd_for_service ~service_name =
   init_random_with ~service_name;
   gen_passwd ;;
 val passwd_for_service : service_name:string -> int -> string = <fun>

Example of use:

 # passwd_for_service  "codecodex.com" 16 ;;
 - : string = "SctZEJOpL4UAmoDC"

PHP

 <?php
 /*
 Class MAKEpasswd:
 Make password from selected characters in a string.
 required arguments:
 length of a password and characters to use in a password.
 
 1 = a - z
 2 = A - Z
 3 = a - z and A - Z
 4 = a - z, A - Z and 0 - 9
 5 = a - z, A - Z, 0 - 9 and chars !#$%&()
 
 usage:
 Make 10 passwords that is 8 characters long and
 includes characters a - z, A - Z, 0 - 9 and !#$%&()
 
 $numTimes = 0;
 $example = new MAKEpasswd(8,5);
 while($numTimes < 10)
 {
        print($example->makePassword() . "<br>\n");
        $numTimes++;
 }
 */
 class MAKEpasswd
 {
        var $intLength;
        var $pool;
 
        function MAKEpasswd($iLength, $iChars)
        {
                $this->intLength = $iLength;
                $this->pool = $this->getPool($iChars);
        }
        function getPool($iChars)
        {
                switch($iChars)
                {
                        case 1: /* a - z */
                                for($i = 0x61; $i <= 0x7A; $i++)
                                {
                                        $str .= chr($i);
                                }
                                return $str;
                                break;
                        case 2: /* A - Z */
                                for($i = 0x41; $i <= 0x5A; $i++)
                                {
                                        $str .= chr($i);
                                }
                                return $str;
                                break;
                        case 3: /* a - z and A - Z */
                                $str = $this->getPool(1);
                                $str .= $this->getPool(2);
                                return $str;
                                break;
                        case 4: /* 0 - 9, A - Z and a - z */
                            $str = $this->getPool(3); // get chars a - z and A - Z first
                                for($i = 0x30; $i <= 0x39; $i++)
                                {
                                        $str .= chr($i); // add chars 0 - 9;
                                }
                                return $str;
                                break;
                        case 5:
                                /* This will add these chars into the string !#$%&() */
                                $str = $this->getPool(4);
                                for($i = 0x21; $i < 0x29; $i++)
                                {
                                        if($i == 0x22 || $i == 0x27) // Exclude characters " and '
                                        {
                                                continue;
                                        }
                                        $str .= chr($i);
                                }
                                return $str;
                                break;
                }
        }
        function makePassword()
        {
                srand ((double) microtime() * 1000000);
                $str="";
                while(strlen($str)< $this->intLength)
                {
                        $str.=$this->pool[rand()%strlen($this->pool)];
                }
                return $str ;
        }
 }
 
 ?>

Source: PHP Builder

Python

import string,random
def makePassword(minlength=5,maxlength=25):
  length=random.randint(minlength,maxlength)
  letters=string.ascii_letters+string.digits # alphanumeric, upper and lowercase
  return ''.join([random.choice(letters) for _ in range(length)])

Ruby

def generate_passwd(length=16)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789'
  Array.new(length) { chars[rand(chars.length)].chr }.join
end

Scheme

(define (gen-pass len)
  (let ((alphanum "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
    (if (zero? len)
        '()
        (cons (string-ref alphanum (random (- (string-length alphanum) 1))) (gen-pass (- len 1))))))

(define (make-pass len)
  (list->string (gen-pass len)))

Tcl

proc rndpassword len {
 set s "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789"
 for {set i 0} {$i <= $len} {incr i} {
    append p [string index $s [expr {int([string length $s]*rand())}]]
 }
 return $p
}

Zsh

zmodload -i zsh/mathfunc

length=13 # Max possible value are equal to size of $chars.
chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?:^~@#$%&*_+=[]/"

while (( i++ < length ))
do
	random=$((1 + int(${(c)#chars} * rand48())))
	password+="$chars[$random]"
	chars[$random]=""
done

print "$password"