-
-
Save darmentrout/f158091518eed020e15397ba6818cee5 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." ); | |
} | |
} | |
// return a random symbol | |
function generateSymbol(){ | |
$symbols = ['!', '@', '%', '~']; | |
return $symbols[random_int( 0, count($symbols)-1 )]; | |
} | |
function generatePassword($length){ | |
$pw_string = substr( preg_replace( "/[^a-zA-Z0-9]/", "", base64_encode( getRandomBytes($length+1) )), 0, $length ); | |
// insert a random symbol and return the string | |
return substr_replace( $pw_string, generateSymbol(), random_int( 1, strlen($pw_string)-1 ), 0 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This fork adds a random symbol in a random spot within the already randomly generated password string.