Generate a random password or random string

From CodeCodex

Revision as of 18:20, 28 July 2006 by 206.160.140.2 (Talk)

Password generation code builds random passwords that match specific requirements.

Implementations

Java

import java.util.*;

/**
 *
 * @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

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() . "
\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.=substr($this->pool,(rand()%(strlen($this->pool))),1); } return($str); } } ?>

Source: PHP Builder