Skip to content

Instantly share code, notes, and snippets.

@mrpapercut
Created May 19, 2017 11:02
Show Gist options
  • Save mrpapercut/b7142ab2513bca85a467d7317b35467d to your computer and use it in GitHub Desktop.
Save mrpapercut/b7142ab2513bca85a467d7317b35467d to your computer and use it in GitHub Desktop.
Generate strong passwords with PHP
<?php
$symbols = str_split('!$%@#');
$chars = str_split('abcdefghijklmnopqrstuvwxyz0123456789');
$pwlen = isset($_POST['len']) ? (int) $_POST['len'] : 64;
$pwlen = $pwlen > 1024 ? 1024 : $pwlen; // Max length: 1024
$useSyms = isset($_POST['sym']) && $_POST['sym'] === '0' ? false : true;
$passArr = array();
function getRand() {
return hexdec(bin2hex(openssl_random_pseudo_bytes(1)));
}
function randFromArr($arr) {
do {
$x = getRand();
} while ($x >= count($arr));
return $arr[$x];
}
function randBelowLimit($limit) {
do {
$x = getRand();
} while ($x >= $limit);
return $x;
}
for ($i = 0; $i < $pwlen; $i++) {
if (getRand() % 2 === 0) {
$passArr[$i] = ucfirst(randFromArr($chars));
} else {
$passArr[$i] = randFromArr($chars);
}
}
if ($useSyms) {
$symlen = randBelowLimit($pwlen / 2);
for ($i = 0; $i < $symlen; $i++) {
$passArr[randBelowLimit($pwlen) - 1] = randFromArr($symbols);
}
}
echo implode('', $passArr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment