Created
February 21, 2023 04:40
-
-
Save ShadSterling/06dc9f888a6114743b7c1498795d9ef1 to your computer and use it in GitHub Desktop.
password-generator
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
#!/usr/bin/env php | |
<?php | |
function dev_rand( $min=0, $max=-1 ) | |
{ | |
if( -1 == $max ) { $max=getrandmax(); } #can't use a function as a default value | |
$range = $max-$min+1; #+1 to be inclusive | |
$file="/dev/random"; ##urandom is the faster/less random variant | |
$handle=fopen($file,"rb"); | |
if( false == $handle ) { throw new Exception("Unable to open ".$file); } | |
$byte = fgetc($handle); ##TODO: get the right number of bits according to $range; 2nd parm $length = ⌈log₂($range)/8⌉ # (bits to represent range)/8 = (bytes to represent range) | |
fclose($handle); | |
$raw = (double) ord($byte); # $byte is a one-byte char; ord($byte) is the byte value of the encoded char as an int | |
$scaled = $range * $raw / 256; # since $r is one byte, it has a range of 256; $scaled ∈[0,$range) | |
$result = $min + $scaled; | |
return (int) $result; | |
} | |
function password_2009() { return password_bits(48); } ## I estimated 48-bits as sufficient (but did not record sources) | |
function password_2012() { return password_bits(72); } ## I was using 13-chars in 2012 (but did not record sources) | |
function password_2019() { return password_bits(100); } ## 18-chars = 100-bits, re https://discourse.codinghorror.com/t/password-rules-are-bullshit/5033/91 | |
## I estimated and ~5.6bits/character with these character options (somewhat based on wikipedia and possibly other sources) | |
function password_bits( $bits=100 ) { return password_chars( ceil($bits/5.6) ); } | |
## Generate ~n-character password using upper- lower- and numerals | |
function password_chars( $chars=18 ) | |
{ | |
$pickfrom="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; #alphanumeric only | |
#$pickfrom="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_%@!$&*~"; #alphanumeric and "special" characters | |
$password=""; | |
for( $n=0; $n<$chars; $n++ ) { | |
$i = dev_rand( 0, strlen($pickfrom)-1 ); | |
$c = $pickfrom[$i]; | |
$password .= $c; | |
} | |
return $password; | |
} | |
function password_default() { return password_2019(); } | |
if( __FILE__ == realpath($argv[0]) ) #if this file was executed directly | |
{ print "".password_default()."\n"; } | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment