PHP Passwords with Character Arrays

Here’s a simple function I recently wrote to randomly generate passwords in PHP.

Simplified a bit, this is equivalent to:

This works because like C, PHP allows a string to be accessed as an array of characters using either brackets or braces:

For 8-character passwords the algorithm above will produce a string containing at least two of the four character types (upper case, lower case , digits and symbols) more than 99.9% of the time. This can be shown by removing from the set of all possible passwords those passwords that contain only one of the four character types.

All possible passwords: (26+26+10+19)8 = 818
Passwords containing only lower case characters: 268
Passwords containing only upper case characters: 268
Passwords containing only digits: 108
Passwords containing only symbols: 198

P=\frac{81^8-(26^8+26^8+10^8+19^8)}{81^8} = 1-\frac{26^8+26^8+10^8+19^8}{81^8} = .999765\ldots

This comports with the results of a run of 10,000,000 samples which yielded 9,997,635 passwords containing characters from at least two groups.

Note that this article is meant as a demonstration of one way to quickly generate general purpose passwords. If you need to generate highly secure passwords you will need to do more homework, including but not limited to replacing the mt_rand function with a cryptographically secure PRNG.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.