Skip to content

Instantly share code, notes, and snippets.

@darmentrout
Forked from zyphlar/generatePassword.php
Last active June 27, 2018 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darmentrout/f158091518eed020e15397ba6818cee5 to your computer and use it in GitHub Desktop.
Save darmentrout/f158091518eed020e15397ba6818cee5 to your computer and use it in GitHub Desktop.
Generating secure passwords in PHP
<?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 );
}
@darmentrout
Copy link
Author

This fork adds a random symbol in a random spot within the already randomly generated password string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment