Explain how to create random passwords.
Generating random passwords in PHP can be done in multiple ways depending on how much security the application demands:-
Md5 function can be passed one parameter as uniqid() function which in turn generates a random number. Passing the parameter as TRUE in uniqid() adds additional uniqueness.
<?php
$passwd = md5(uniqid(rand(), true));
Echo $passwd;
?>
Explain how to create random passwords.
Random password can be created by applying a simple logic. The following steps describe the process:
- Define a function for creation of random password
- Initialize the PHP random generator by using the time value
- Define three strings for various passwords
- Set the password and length counter variables
- Define a loop which appends the required length of random characters one after another to the password string.
- Make sure that all characters are different for generating password
- Lastly return the generated password
The sample code is
<?php
function generatePassword($;length=6,$;level=2)
{
list($;usec, $;sec) = explode(' ', microtime());
srand((float) $;sec + ((float) $;usec * 100000));
$;validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
$;validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$;validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_!@#$%&*()-=+/";
$;password = "";
$;counter = 0;
while ($;counter < $;length)
{
$;actChar = substr($;validchars[$;level], rand(0, strlen($;validchars[$;level])-1), 1);
// All character must be different
if (!strstr($;password, $;actChar))
{
$;password .= $;actChar;
$;counter++;
}
}
return $;password;
}
?>