-
Notifications
You must be signed in to change notification settings - Fork 0
/
strong-string-generator.php
118 lines (106 loc) · 3.17 KB
/
strong-string-generator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
/**
Name: Strong String Generator
Version: 1.0.0
*/
namespace Smartbee;
class StrongStringGenerator
{
public $MLenght = 26;
public $AlpHabetAndSpecials ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789?#$!@`.~^&*-_+={}[]|()%";
public const VERSION = "1.0";
public function __construct($Lenght="", $alphabet="")
{
$this->MLenght = !empty($Lenght) ? $Lenght : $this->MLenght;
$this->AlpHabetAndSpecials = !empty($alphabet) ? $alphabet : $this->AlpHabetAndSpecials;
}
private function CreateRandomInteger($min, $max)
{
if (is_numeric($max)) {
$max += 0;
}
if (
is_float($max) &&
$max > ~PHP_INT_MAX &&
$max < PHP_INT_MAX
) {
$max = (int) $max;
}
if (is_numeric($min)) {
$min += 0;
}
if (
is_float($min) &&
$min > ~PHP_INT_MAX &&
$min < PHP_INT_MAX
) {
$min = (int) $min;
}
if (!is_int($max)) {
throw new TypeError('Maximum value must be an integer.');
}
if (!is_int($min)) {
throw new TypeError('Minimum value must be an integer.');
}
if ($min > $max) {
throw new Error('Minimum value must be less than or equal to the maximum value');
}
if ($max === $min) {
return $min;
}
$attempts = $bits = $bytes = $mask = $valueShift = 0;
$range = $max - $min;
if (!is_int($range)) {
$bytes = PHP_INT_SIZE;
$mask = ~0;
} else {
while ($range > 0) {
if ($bits % 8 === 0) {
++$bytes;
}
++$bits;
$range >>= 1;
$mask = $mask << 1 | 1;
}
$valueShift = $min;
}
do {
if ($attempts > 128) {
throw new Exception(
'random_int: RNG is broken - too many rejections'
);
}
$randomByteString = random_bytes($bytes);
if ($randomByteString === false) {
throw new Exception(
'Random number generator failure'
);
}
$val = 0;
for ($i = 0; $i < $bytes; ++$i) {
$val |= ord($randomByteString[$i]) << ($i * 8);
}
$val &= $mask;
$val += $valueShift;
++$attempts;
} while (!is_int($val) || $val > $max || $val < $min);
return (int) $val;
}
public function CreateStrongString()
{
$length = $this->MLenght;
$alphabet = $this->AlpHabetAndSpecials;
if ($length < 1) {
throw new InvalidArgumentException('Length must be a positive integer');
}
$str = '';
$alphamax = strlen($alphabet) - 1;
if ($alphamax < 1) {
throw new InvalidArgumentException('Invalid alphabet');
}
for ($i = 0; $i < $length; ++$i) {
$str .= $alphabet[$this->CreateRandomInteger(0, $alphamax)];
}
return $str;
}
}