Created
December 20, 2014 22:36
-
-
Save zyphlar/7217f566fc83a9633959 to your computer and use it in GitHub Desktop.
Generating secure passwords in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// usage: $newpassword = generatePassword(12); // for a 12-char password, upper/lower/numbers. | |
// functions that use rand() or mt_rand() are not secure according to the PHP manual. | |
function getRandomBytes($nbBytes = 32) | |
{ | |
$bytes = openssl_random_pseudo_bytes($nbBytes, $strong); | |
if (false !== $bytes && true === $strong) { | |
return $bytes; | |
} | |
else { | |
throw new \Exception("Unable to generate secure token from OpenSSL."); | |
} | |
} | |
function generatePassword($length){ | |
return substr(preg_replace("/[^a-zA-Z0-9]/", "", base64_encode(getRandomBytes($length+1))),0,$length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, excellent code, I will definitely use it in my projects :)