Jump to content
Larry Ullman's Book Forums

Generate Multiple Usernames And Passwords


Recommended Posts

I need to generate serveral hundred random usernames and passwords, and store each pair in a table. Presumably the best way is to use a loop? Do you have any recommendations to ensure processing efficiency? Or are pre written functions you would recommend? Thanks.

Link to comment
Share on other sites

What is randomness? Can usernames be random letters, numbers and characters or should they at least resemble real words? Such things are important to know.

 

A way to do this is to specify a number Range use rand() to get a number then chr() to get a character.

 

$min = 30;

$max = 70;

$userlength = rand(3, 10);

 

$username = '';

for ($i=0; $i<$userlength; $i++) {

$username .= chr(rand($min, $max));

}

 

Another is to create and fill an array with allowed characters for a username then to randomly select an item between 0 and array length. The same can be done for passwords.

 

Sorry. Writing on phone, so it's tricky to create something good for you. That above would give you the basic idea. You might get some weird chars though. Find a range in ASCII table or use the array solution. Try a google search for username Generator php or something. This probably exist.

  • Upvote 1
Link to comment
Share on other sites

Thanks Antonio - these are good questions and very helpful suggestions. I need to confirm the requirements but I suspect the username and password are limited to alphanumerics and the usernames have to be unique. Once I get the specifics I'll give your suggestions a go. Thanks again.

Link to comment
Share on other sites

Had some more time today.

 

Usernames are unique as an equal one will just overwrite the old one. This script should therefor not be used twice or you must write a check somewhere to ensure that old users are not overwritten. There is improvement to be done here, but this should be a good start.

 

Added a small key check. Will work if you add old username keys to the users array before generating any more usernames and passwords.

 

Something to get you started:

 

<?php

// Set some variables
$number_of_users = 100;
$min_username_length = 3;
$max_username_length = 12;
$min_password_length = 8;
$max_password_length = 12;

// Create user array
$users = array();

// Create usernames
for ( $i = 0; $i < $number_of_users; $i++ ) {

  // find random length
  $namelength = mt_rand($min_username_length, $max_username_length);
  $passlength = mt_rand($min_password_length, $max_password_length);

  // Get username
  $username = random($namelength);

  // Make sure username is unique
  if ( array_key_exists( $username, $users ) == false )
  {
  // Add to array
  $users[$username] = crypt(random($passlength));
  }
}

// Print usernames to screen
foreach ( $users as $user => $pass )
{
echo 'Username: '. $user. ' Password: '. $pass . '<br />';
}

function random( $length )
{
// Set allowed chars
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

// Create username
$username = "";
for ( $i = 0; $i < $length; $i++ )
{
	$username .= $chars[mt_rand(0, strlen($chars))];
}
return $username;
}

?>

 

The check is untested, but pretty sure there's no error there.

  • Upvote 1
Link to comment
Share on other sites

Antonio, this is awesome. You've taught me alot, thank you. A couple of questions:

  1. $chars is defined as a string, but used as an array in the penultimate line. so I changed it to
    		$username .= substr($chars,mt_rand(0, strlen($chars)),1);
    

    which works unless you think there is a better way.

  2. the username, password pairs need to be stored in a d/b as well as displayed on screen. Do I need to do 100 inserts or is there a way to improve performance by doing one batch insert?
  3. how would I force the password to contain at least 1 number, 1 lowercase and 1 uppercase letter?

Thanks again - really appreciate your help!

  • Upvote 1
Link to comment
Share on other sites

Usergenerator.php:

 

<?php

class UserGenerator
{

private $pass_min = 8;
private $pass_max = 15;
private $user_min = 3;
private $user_max = 12;
private $user_case = FALSE;
private $salt = '$2a$07$usesomesillystringforsalt$';

private $users = array();

public function __construct($pass_min, $pass_max, $user_min, $user_max, $case_sensitive )
{
	$this->pass_min = $pass_min;
	$this->pass_max = $pass_max;
	$this->user_min = $user_min;
	$this->user_case = $case_sensitive;
	$this->user_max = $user_max;
}

public function generate( $capacity = 100 )
{

	for ( $i = 1; $i <= $capacity; $i++ )
	{
		$username = $this->genUsername( $this->user_min, $this->user_max, $this->user_case );

		// Make sure username is unique
		if ( array_key_exists( $username, $this->users ) == false )
		{
			$password = $this->genPassword( $this->pass_min, $this->pass_max );
			$encrypted = $this->cryptPassword($password);

			$this->users[$username] = array
			(
				'user_num' => $i,
				'username' => $username,
				'password' => $password,
				'encrypted' => $encrypted,
			);
		   }	
	}
	return $this->users;
}

public function getQuery( $tablename, $columns)
{
	$values = '';

	foreach ( $this->users as $u )
	{
		$values .= "(null,'{$u['username']}','{$u['encrypted']}'),";
	}

	return 'INSERT INTO '.$tablename.' ('.$columns.') VALUES'.rtrim($values, ",");

}

public function checkPassword ( $password )
{
	// Query users password in DB. It will be stored encrypted, so use it here.
	$password_queried_from_db = '$2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi'; // pass = rasmuslerdorf

	if (CRYPT_BLOWFISH == 1)
	{
   	 if (crypt($password, $this->salt) == $password_queried_from_db)
   	 {
			return true;
   	 }
	}
	return false;

}

private function cryptPassword( $password )
{
	return crypt($password, $this->salt);
}


private function genUsername( $min, $max, $case_sensitive = false )
{
	// Set length
	$length = rand($min, $max);

	// Set allowed chars (And whether they should use case)
	if ( $case_sensitive )
	{
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	}
	else
	{
		$chars = "abcdefghijklmnopqrstuvwxyz";
	}

	// Get string length
	$chars_length = strlen($chars);

	// Create username char for char
	$username = "";

	for ( $i = 0; $i < $length; $i++ )
	{
		$username .= $chars[mt_rand(0, $chars_length)];
	}

	return $username;

}

private function genPassword( $min, $max)
{
	// Set length
	$length = rand($min, $max);

	// Set charachters to use
	$lower = 'abcdefghijklmnopqrstuvwxyz';
	$upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$chars = '123456789@#$%&';

	// Calculate string length
	$lower_length = strlen($lower);
	$upper_length = strlen($upper);
	$chars_length = strlen($chars);

	// Generate password char for char
	$password = '';
	$alt = time() % 2;
	for ($i = 0; $i < $length; $i++)
	{
		if ($alt == 0)
		{
			$password .= $lower[mt_rand(0, $lower_length)]; $alt = 1;
		}
		if ($alt == 1)
		{
			$password .= $upper[mt_rand(0, $upper_length)]; $alt = 2;
		}
		else
		{
			$password .= $chars[mt_rand(0, $chars_length)]; $alt = 0;
		}
	}
	return $password;
}

private function isNum( $num )
{
	if ( is_int( (String) $num ) && ctype_digit((int) $num) && $num > 0 )
	{
		return true;	
	}
	return false;
}
}

 

Test.php uses this class. It will allow you to generate a specified number of users based on settings used when creating the object. The standard values will be used if non are specified. generate() let you you specify a number of users to generate with default as 100.

 

getQuery() will generate a SQL query. You may need to change this function if it does not work for you.

 

test.php:

<?php

include('UserGenerator.php');

// Create userGenerator object
$gen = new UserGenerator(); // or something like new UserGenerator( 5, 12, 7, 12, true);

// Generate 100 usernames and passwords
$users = $gen->generate(100);

// Generate query string
$query = $gen->getQuery('users', 'id, username, password');

// Compare passwords. Change the function to query for the users password here.
// The first password is hard coded in the function.  'rasmuslerdorf' is TRUE, the others false
echo ($gen->checkPassword('rasmuslerdorf')) ? "Correct password <hr />" : "Wrong password <hr />";
echo ($gen->checkPassword('Rasmuslerdorf')) ? "Correct password <hr />" : "Wrong password <hr />";
echo ($gen->checkPassword('blablalba')) ? "Correct password <hr />" : "Wrong password <hr />";

foreach ( $users as $user ) {
echo
	 ' Username '.$user['user_num'].': '.$user['username'].
	 ' Password: '.$user['password'].
	 ' Encrypted: '.$user['encrypted'].' <br />';
}

?>

 

If you PM me your email, I can send the class to you.

Link to comment
Share on other sites

 Share

×
×
  • Create New...