john.mcclumpha

php : PHP Password Functions

Published: 2 yearss ago

Originally published April 2007 - http://blogs.igeek.com.au/DarkAz/

Here's a couple of basic password generating functions I've created which have come in quite handy.

Item 1: Basic random password generator

The first is a basic random password generator - you simply define the length required for the password and the function returns an alphanumeric string of random characters:

function Random_Password($length) {
	list($usec, $sec) = explode(' ', microtime());
	srand((float) $sec + ((float) $usec * 100000));
	$possible_characters = "23456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
	// note that 0 and O, 1 and l (that's zero and 'oh', one and 'el') 
	// have been omitted as they are easily confused
	$passstring = "";
	while(strlen($passstring)<$length) {
	    $passstring .= substr($possible_characters, rand(0,strlen($possible_characters)),1);
	}
	return($passstring);
}
Examples:
RandomPassword(5) returned Dgh6W
RandomPassword(10) returned qWAGx3QyeC

Item 2: L337-speak password generator

OK I'm really over the whole concept of L337 (Elite) speak - but it is quite handy for passwords - this function will convert any string into a L337 style password

function LeetPass($original,$justalphanum) {
	// leet speak password generator
	// simply enter a word and get a mixed case equivalent with numbers replacing some letters
	// also strips any non alphanumeric characters within the string
	
	if ($justalphanum) { // check to see if we are stripping out non alpha-numeric characters
		$original = preg_replace("/[^a-zA-Z0-9]/","",$original);
	}
	$find = array("o","i","z","e","a","s","g","b"," ");
	$replace = array("0","1","2","3","4","5","6","8","");
	
	// go through and randomly replace lowercase letters with uppercase
	$stage1 = str_replace($find,$replace,strtolower($original));
	
	$stage2 = "";
	for ($i=0;$i < strlen($stage1);$i++) {
		if (ctype_digit(substr($stage1,$i,1))) { // it's a number
			$stage2 .= substr($stage1,$i,1);
		} else { // it's not a number, so probably a letter
			if (rand(0,1)) {
				$stage2 .= strtoupper(substr($stage1,$i,1));
			} else {
				$stage2 .= substr($stage1,$i,1);
			}	
		}
	}

	return ($stage2);
}

Examples:
LeetPass("L337-speak password generator",false) returned L337-5P34k p455W0Rd 63n3r4t0r
LeetPass("elite-speak, it's truly a thing of the past!",true) returned 3l1T35P34k1t5tRULy4TH1n60FtH3P45T

recent posts

Follow me on Twitter
Follow me on Facebook

Have you checked out Mister Wong? Simply the best way to manage your bookmarks online:
Mister Wong