Skip to content

Instantly share code, notes, and snippets.

@soulik
Last active October 13, 2016 19:37
Show Gist options
  • Save soulik/a1cbcf286fc10d588efff94c412fd3b6 to your computer and use it in GitHub Desktop.
Save soulik/a1cbcf286fc10d588efff94c412fd3b6 to your computer and use it in GitHub Desktop.
<?php
class PasswordGenerator {
var $pwdMinLength = 12;
var $pwdMaxLength = 20;
var $pwdMap = [
[
'chars' => 'abcdefghijklmnopqrstuvwxyz',
'weight' => 30,
],
[
'chars' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'weight' => 30,
],
[
'chars' => '0123456789',
'weight' => 30,
],
[
'chars' => ',._-+',
'weight' => 10,
],
];
var $pwdMapSets = [];
var $pwdMapWeights = [];
var $pwdMapTotalWeight = 0;
function __construct() {
$prevWeight = 0;
foreach ($this->pwdMap as $pwdMap){
$this->pwdMapSets[] = str_split($pwdMap['chars']);
$weight = $pwdMap['weight'];
$this->pwdMapWeights[] = [$prevWeight, $prevWeight + $weight-1];
$prevWeight += $weight;
}
$this->pwdMapTotalWeight = $prevWeight;
}
public function generatePassword($minLength = -1, $maxLength = -1){
if ($minLength<0) $minLength = $this->pwdMinLength;
if ($maxLength<0) $maxLength = $this->pwdMaxLength;
$original_bytes = str_split(random_bytes(random_int($minLength, $maxLength)));
$mapSelector = function(): int{
$selection = random_int(0, $this->pwdMapTotalWeight);
foreach ($this->pwdMapWeights as $index => $weights){
if (($selection >= $weights[0]) && ($selection <= $weights[1])){
return $index;
}
}
return 0;
};
$pwd = array_map(function($n) use ($mapSelector) {
$charIndex = ord($n);
$currentMap = $this->pwdMapSets[$mapSelector()];
$index = $charIndex % count($currentMap);
return $currentMap[$index];
}, $original_bytes);
return implode($pwd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment