Difference between revisions of "Generate a random password or random string"

From CodeCodex

(Bash Shell: better way)
(Groovy)
 
(21 intermediate revisions by 16 users not shown)
Line 2: Line 2:
  
 
==Implementations==
 
==Implementations==
===Ruby===
+
 
 +
===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.
 
<pre>
 
<pre>
def generate_passwd(length=16)
+
</dev/urandom tr -dc A-Za-z0-9_ | head -c8
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789'
+
  password = ''
+
  length.times { password << chars[rand(chars.length)] }
+
  password
+
end
+
 
</pre>
 
</pre>
 +
Alternatively you can do
 +
<pre>
 +
cat /dev/urandom | base64 | head -c8
 +
</pre>
 +
which wastes less entropy.
 +
 +
===Common Lisp===
 +
You could use the [[#Scheme|Scheme]] version with only little modifications
 +
(most notably, <code>(coerce foo 'string)</code> instead of <code>list->string</code>), or use a somewhat more CL-ish iterative style:
 +
 +
<pre>
 +
(defun random-password (length)
 +
  (let ((chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
 +
    (coerce (loop repeat length collect (aref chars (random (length chars))))
 +
            'string)))
 +
</pre>
 +
 +
An alternative is to take advantage of Common Lisp's string-streams and number printing support:
 +
 +
<pre>
 +
(defun random-password (length)
 +
  (with-output-to-string (stream)
 +
    (let ((*print-base* 36))
 +
      (loop repeat length do (princ (random 36) stream)))))
 +
</pre>
 +
 +
Or in imperative style, side-effecting a pre-allocated string:
 +
 +
<pre>
 +
(defun random-password (length)
 +
  (let ((chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
 +
        (password (make-string length)))
 +
    (dotimes (i length)
 +
      (setf (aref password i) (aref chars (random (length chars)))))
 +
    password))
 +
</pre>
 +
 +
===Erlang===
 +
<pre>
 +
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)).
 +
</pre>
 +
 
===Groovy===
 
===Groovy===
 
<pre>
 
<pre>
String passwd = ""
+
def pool = ['a'..'z','A'..'Z',0..9,'_'].flatten()
String pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"
+
 
Random rand = new Random(System.currentTimeMillis())
 
Random rand = new Random(System.currentTimeMillis())
  
for(i in 0..10)          
+
def passChars = (0..10).collect { pool[rand.nextInt(pool.size())] }
    passwd += pool[rand.nextInt(pool.length())]
+
def password = passChars.join()
 +
</pre>
 +
OR
 +
<pre>
 +
def password = org.apache.commons.lang.RandomStringUtils.randomAlphanumeric(length)
 
</pre>
 
</pre>
  
 
===Java===
 
===Java===
<pre>
+
 
 +
<pre class="java">
 
     SecureRandom random = new SecureRandom();
 
     SecureRandom random = new SecureRandom();
 
     String str = new BigInteger(130, random).toString(32);
 
     String str = new BigInteger(130, random).toString(32);
 
</pre>
 
</pre>
====Class====
+
 
<pre>
+
OR
 +
<pre class="java">
 
public class RandomString {
 
public class RandomString {
  
Line 41: Line 90:
 
                       java.util.Random rn = new java.util.Random();
 
                       java.util.Random rn = new java.util.Random();
 
                   int n = hi - lo + 1;
 
                   int n = hi - lo + 1;
                   int i = rn.nextInt() % n;
+
                   int i = rn.nextInt(n);
 
                   if (i < 0)
 
                   if (i < 0)
 
                           i = -i;
 
                           i = -i;
Line 63: Line 112:
  
 
====Applet====
 
====Applet====
<pre>
+
This applet will create a random password or random text.
 +
<pre class="java">
 
import java.util.Random;
 
import java.util.Random;
  
Line 317: Line 367:
 
</pre>
 
</pre>
 
Source: [http://bellsouthpwp.net/j/h/jhadstat/javaapps.htm John E. Hadstate]
 
Source: [http://bellsouthpwp.net/j/h/jhadstat/javaapps.htm John E. Hadstate]
 +
 +
===JavaScript===
 +
<pre class="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;
 +
}
 +
</pre>
 +
Original Source: [http://stackoverflow.com/questions/1349404/generate-a-string-of-5-random-characters-in-javascript StackOverflow]
  
 
===OCaml===
 
===OCaml===
<pre>
+
<pre >
 
# let gen_passwd length =
 
# let gen_passwd length =
 
     let gen() = match Random.int(26+26+10) with
 
     let gen() = match Random.int(26+26+10) with
Line 334: Line 399:
 
</pre>
 
</pre>
  
====OCaml====
+
Alternativley:
Another way in OCaml:
+
  
 +
<pre>
 
  let gen_passwd =
 
  let gen_passwd =
 
   let alphanum =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" in
 
   let alphanum =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" in
Line 347: Line 412:
 
     (str)             
 
     (str)             
 
  ;;
 
  ;;
 +
</pre>
  
 
And here is how to allways generate the same random password for a given service:<br>
 
And here is how to allways generate the same random password for a given service:<br>
 
(if you use it, change the private_seed for your own one)
 
(if you use it, change the private_seed for your own one)
  
 +
<pre>
 
  let init_random_with ~service_name =
 
  let init_random_with ~service_name =
 
   (* use your own private seed, not this one *)
 
   (* use your own private seed, not this one *)
Line 364: Line 431:
 
   gen_passwd ;;
 
   gen_passwd ;;
 
  val passwd_for_service : service_name:string -> int -> string = <fun>
 
  val passwd_for_service : service_name:string -> int -> string = <fun>
 +
</pre>
  
 
Example of use:
 
Example of use:
  
 +
<pre>
 
  # passwd_for_service  "codecodex.com" 16 ;;
 
  # passwd_for_service  "codecodex.com" 16 ;;
 
  - : string = "SctZEJOpL4UAmoDC"
 
  - : string = "SctZEJOpL4UAmoDC"
 
===Scheme===
 
<pre>
 
(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)))
 
 
</pre>
 
</pre>
===Common Lisp===
 
You could use the [[#Scheme|Scheme]] version with only little modifications
 
(most notably, <code>(coerce foo 'string)</code> instead of <code>list->string</code>), or use a somewhat more CL-ish
 
iterative style:
 
 
<HIGHLIGHTSYNTAX language="lisp">
 
(require :iterate)
 
(use-package :iterate)
 
 
(defun random-passwd (len)
 
  (let* ((chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
 
        (n (length chars)))
 
    (coerce
 
    (iter (for i from 1 to len)
 
          (collect (elt chars (random n))))
 
    'string)))
 
</HIGHLIGHTSYNTAX>
 
 
===Perl===
 
TIMTOWTDI. See [http://search.cpan.org/dist/Crypt-GeneratePassword Crypt::GeneratePassword] or [http://search.cpan.org/dist/Crypt-PassGen Crypt::PassGen] or [http://search.cpan.org/dist/Crypt-RandPasswd Crypt::RandPasswd] or [http://search.cpan.org/dist/Crypt-YAPassGen Crypt::YAPassGen] or [http://search.cpan.org/dist/randompass Data::RandomPass] or [http://search.cpan.org/dist/Data-SimplePassword Data::SimplePassword] or [http://search.cpan.org/dist/String-MkPasswd String::MkPasswd].
 
  
 
===PHP===
 
===PHP===
 +
<pre class="php">
 
  <?php
 
  <?php
 
  /*
 
  /*
Line 490: Line 529:
 
                 while(strlen($str)< $this->intLength)
 
                 while(strlen($str)< $this->intLength)
 
                 {
 
                 {
                $str.=substr($this->pool,(rand()%(strlen($this->pool))),1);
+
                        $str.=$this->pool[rand()%strlen($this->pool)];
 
                 }
 
                 }
                 return($str);
+
                 return $str ;
 
         }
 
         }
 
  }
 
  }
 
   
 
   
 
  ?>
 
  ?>
 
+
</pre>
 
Source: [http://www.phpbuilder.com/snippet/download.php?type=snippet&id=889 PHP Builder]
 
Source: [http://www.phpbuilder.com/snippet/download.php?type=snippet&id=889 PHP Builder]
  
 
===Python===
 
===Python===
<pre>
+
<pre class="python">
 
import string,random
 
import string,random
 
def makePassword(minlength=5,maxlength=25):
 
def makePassword(minlength=5,maxlength=25):
Line 508: Line 547:
 
   return ''.join([random.choice(letters) for _ in range(length)])
 
   return ''.join([random.choice(letters) for _ in range(length)])
 
</pre>
 
</pre>
===Bash Shell===
+
 
This is a simpler password generator. 
+
===Ruby===
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.
+
<pre class="ruby">
<highlightsyntax>
+
def generate_passwd(length=16)
</dev/urandom tr -dc A-Za-z0-9_ | head -c8
+
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789'
</highlightsyntax>
+
  Array.new(length) { chars[rand(chars.length)].chr }.join
Alternatively you can do
+
end
<highlightsyntax>
+
</pre>
cat /dev/urandom | base64 | head -c8
+
 
</highlightsyntax>
+
===Scheme===
which wastes less entropy.
+
<pre>
 +
(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)))
 +
</pre>
 +
 
 +
=== Tcl ===
 +
<pre class="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
 +
}
 +
</pre>
  
 
===Zsh===
 
===Zsh===
Line 537: Line 596:
 
</pre>
 
</pre>
  
 +
[[Category:String]]
 +
 +
[[Category:Bash]]
 
[[Category:Common Lisp]]
 
[[Category:Common Lisp]]
 +
[[Category:Erlang]]
 +
[[Category:Groovy]]
 
[[Category:Java]]
 
[[Category:Java]]
[[Category:PHP]]
+
[[Category:JavaScript]]
[[Category:Ruby]]
+
 
[[Category:Objective Caml]]
 
[[Category:Objective Caml]]
[[Category:Perl]]
+
[[Category:PHP]]
 
[[Category:Python]]
 
[[Category:Python]]
 +
[[Category:Ruby]]
 
[[Category:Scheme]]
 
[[Category:Scheme]]
[[Category:BASH]]
 
 
[[Category:Zsh]]
 
[[Category:Zsh]]

Latest revision as of 17:24, 9 July 2012

Password generation code builds random passwords that match specific requirements.

Implementations[edit]

Bash[edit]

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[edit]

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[edit]

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[edit]

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[edit]

    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[edit]

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[edit]

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[edit]

# 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[edit]

 <?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[edit]

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[edit]

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

Scheme[edit]

(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[edit]

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[edit]

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"