Fix randomString() to generate cryptographically secure URL-safe tokens, reduced url keys to 32 Characters for performance and easy copy and paste and compatibility while still mainitaining ubreakable cryptographic keys

This commit is contained in:
johnnyq
2025-12-18 14:24:53 -05:00
parent 32f996d034
commit a79ce23ae5
16 changed files with 39 additions and 118 deletions

View File

@@ -4,20 +4,13 @@
DEFINE("WORDING_ROLECHECK_FAILED", "You are not permitted to do that!");
// Function to generate both crypto & URL safe random strings
function randomString($length = 16) {
// Generate some cryptographically safe random bytes
// Generate a little more than requested as we'll lose some later converting
$random_bytes = random_bytes($length + 5);
// Convert the bytes to something somewhat human-readable
$random_base_64 = base64_encode($random_bytes);
// Replace the nasty characters that come with base64
$bad_chars = array("/", "+", "=");
$random_string = str_replace($bad_chars, random_int(0, 9), $random_base_64);
// Truncate the string to the requested $length and return
return substr($random_string, 0, $length);
function randomString(int $length = 16): string {
$bytes = random_bytes((int) ceil($length * 3 / 4));
return substr(
rtrim(strtr(base64_encode($bytes), '+/', '-_'), '='),
0,
$length
);
}
// Older keygen function - only used for TOTP currently