MJH
MJH

Reputation: 633

Will this PHP code generate a truly random password?

I wrote this code to generate a random password.

$s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$len = strlen($s);
$m = '';

for ($i = 0; $i < $length; $i ++) {
    $m .= $s[mt_rand(0, $len -1)];
}

return $m;

Is the returned password truly random?

Upvotes: 0

Views: 164

Answers (3)

gph
gph

Reputation: 1359

As others have pointed out, the concept of 'truly' random doesn't exist for computers. It would actually be quite disastrous if bits were indeed random even a little.

That being said, for most random string generators you probably want something that simulates sampling from a uniform distribution so each outcome is (in theory) equally likely. Different PRNG's simulate distributions with different degrees of success with the trade-off usually coming in the form of speed.

Assuming you are comfortable with mt_rand (I don't know of any reason to not be) and the standard printable ascii character set one simple approach that produces random strings each with equally likely characters across the full printable ascii set is this:

function create_random_string($len) {

    $string = '';

    for ($j = 0; $j < $len; $j++) {
        $string = $string . chr(mt_rand(33,126)); 
    }

    return $string;

}

The meat of this is the rand(33,126) expression. It returns a decimal translatable to the printable ascii character set via chr as shown here: http://www.ascii-code.com/.

Each character is equally likely per the rand function making it as 'random' as possible with the broadest possible printable character set (again, assuming you are limiting the application to the ascii character set).

Upvotes: 0

Halcyon
Halcyon

Reputation: 57721

Some functions are specifically built to deal with cryptography-level randomness.

openssl_random_pseudo_bytes is a good one (requires the openssl lib obviously). You can use it to generate password with strong randomness.

MT (Mersenne Twister) used by mt_rand is considered a PRNG (Pseudo Random Number Generator) whereas openssl_random_pseudo_bytes will attempt to use a CSPRNG (Crypto Secure PRNG).

This function produces bytes which you can easily base64_decode to get passwords with the base64 character set.

Does all this really matter? Unless you're Facebook or a bank, probably not. mt_rand is probably good enough. This does serve to set you on a path to learn more about cryptography, if you're interested.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799550

Any PRNG such as the Mersenne Twister (hence the "mt" in the function name) is not truly random. But it is random enough for most purposes. If you need truly random then you should use your operating system's randomness facilities instead.

Upvotes: 2

Related Questions