@@ -22,74 +22,29 @@ public function __toString(): string
22
22
23
23
public function create_sid (): string
24
24
{
25
- $ prefix = $ this ->config ->getSidPrefix ();
26
- $ desiredOutputLength = $ this ->config ->getSidLength () - strlen ( $ prefix );
27
- $ bitsPerCharacter = $ this ->config ->getSidBitsPerCharacter ();
25
+ $ length = $ this ->config ->getSidLength ();
26
+ $ charset = $ this ->config ->getSidCharset ( );
27
+ $ prefix = $ this ->config ->getSidPrefix ();
28
28
29
- $ bytesNeeded = (int ) ceil ($ desiredOutputLength * $ bitsPerCharacter / 8 );
30
- $ randomInputBytes = random_bytes (max (1 , $ bytesNeeded ));
29
+ $ lengthWithoutPrefix = $ length - \strlen ($ prefix );
31
30
32
- // The below is translated from function bin_to_readable in the PHP source
33
- // (ext/session/session.c)
34
- static $ hexconvtab = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,- ' ;
35
-
36
- $ out = '' ;
37
-
38
- $ p = 0 ;
39
- $ q = strlen ($ randomInputBytes );
40
- $ w = 0 ;
41
- $ have = 0 ;
42
-
43
- $ mask = (1 << $ bitsPerCharacter ) - 1 ;
44
-
45
- $ charsRemaining = $ desiredOutputLength ;
46
- while ($ charsRemaining --) {
47
- if ($ have < $ bitsPerCharacter ) {
48
- if ($ p < $ q ) {
49
- $ byte = ord ($ randomInputBytes [$ p ++]);
50
- $ w |= ($ byte << $ have );
51
- $ have += 8 ;
52
- } else {
53
- // Should never happen. Input must be large enough.
54
- break ;
55
- }
56
- }
57
-
58
- // consume $bitsPerCharacter bits
59
- $ out .= $ hexconvtab [$ w & $ mask ];
60
- $ w >>= $ bitsPerCharacter ;
61
- $ have -= $ bitsPerCharacter ;
31
+ $ pieces = [];
32
+ $ max = \strlen ($ charset ) - 1 ;
33
+ for ($ i = 0 ; $ i < $ lengthWithoutPrefix ; ++$ i ) {
34
+ $ pieces [] = $ charset [\random_int (0 , $ max )];
62
35
}
63
36
64
- return $ prefix . $ out ;
37
+ return $ prefix . \implode ( '' , $ pieces ) ;
65
38
}
66
39
67
40
public function validate_sid (string $ id ): bool
68
41
{
69
- if (strlen ($ id ) !== $ this ->config ->getSidLength ()) {
42
+ if (\ strlen ($ id ) !== $ this ->config ->getSidLength ()) {
70
43
return false ;
71
44
}
72
45
73
- // Prefix might not validate under the rules for bits=4 or bits=5
74
- $ prefix = $ this ->config ->getSidPrefix ();
75
- if ($ prefix ) {
76
- $ id = substr ($ id , strlen ($ prefix ));
77
- }
78
-
79
- switch ($ this ->config ->getSidBitsPerCharacter ()) {
80
- case 4 :
81
- // 0123456789abcdef
82
- return preg_match ('/^[0-9a-f]+$/ ' , $ id ) === 1 ;
83
-
84
- case 5 :
85
- // 0123456789abcdefghijklmnopqrstuv
86
- return preg_match ('/^[0-9a-v]+$/ ' , $ id ) === 1 ;
87
-
88
- case 6 :
89
- // 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-
90
- return preg_match ('/^[0-9a-zA-Z,-]+$/ ' , $ id ) === 1 ;
91
- }
46
+ $ pregSafeString = \preg_quote ($ this ->config ->getSidCharset (), '/ ' );
92
47
93
- return false ;
48
+ return \preg_match ( ' /^[ ' . $ pregSafeString . ' ]+$/ ' , $ id ) === 1 ;
94
49
}
95
50
}
0 commit comments