Since the extra characters are predominantly the padding character =, if we for some reason had a constraint that the password be an exact length, then we can truncate it to the length we want. The result will be exact for $n being a multiple of 4 and up to 3 characters longer otherwise. The 3/4 factor is due to the fact that base64 encoding results in a string that has a length at least a third bigger than the byte string. If we didn't mind having +, / and = characters appear in the final string and we want a result at least $n characters long, we could simply use: base64_encode(strong_random_bytes(intval(ceil($n * 3 / 4)))) Throw new Exception('Strong algorithm not available for PRNG.') įor the second part, we'll use base64_encode since it takes a byte string and will produce a series of characters that have an alphabet very close to the one specified in the original question. System did not use a cryptographically strong algorithm $bytes = openssl_random_pseudo_bytes($length, $strong) $strong = false // Flag for whether a strong algorithm was used Note that whilst most systems use a cryptographically strong algorithm, you have to check so we'll use a wrapper: /** use that data and represent it as some printable stringįor the first part, PHP > 5.3.0 provides the function openssl_random_pseudo_bytes.use some secure source of randomness to get random data.Let's break the problem down into the constituent parts which are: This answer will circumvent the count/strlen issue as the security of the generated password, at least IMHO, transcends how you're getting there. a requirement for some 3rd party library and I thought it might be interesting to show what it might take to do it yourself.a RNG that isn't considered cryptographically secure.a smaller character space than you wanted so that either brute-forcing is easier or the password must be longer for the same entropy.I'm going to post an answer because some of the existing answers are close but have one of: Throw new Exception('$keyspace must be at least two characters long') ![]() $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' * string $keyspace A string of all possible characters * int $length How many characters do we want? * For PHP 7, random_int is a PHP core function ![]() * pseudorandom number generator (random_int) * Generate a random string, using a cryptographically secure With a secure random integer generator on hand, generating a secure random string is easier than pie:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |