Fix weak RNG in key32gen (TOTP secret generation)

Replace srand()/rand() with random_int() for cryptographically secure,
unbiased key generation. The previous implementation seeded rand() from
microtime(), making TOTP secrets predictable if the generation time
could be approximated. Also removes modulo bias and dead while(1)
wrapper.

Output format is unchanged: 32 chars from the base32 alphabet (A-Z,
2-7), so existing TOTP enrollments are unaffected.
This commit is contained in:
johnnyq
2026-07-14 16:57:16 -04:00
parent bf0d799caf
commit 5eb9f6b6d5

View File

@@ -16,15 +16,10 @@ function randomString(int $length = 16): string {
// Older keygen function - only used for TOTP currently
function key32gen() {
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$chars .= "234567";
while (1) {
$key = '';
srand((float) microtime() * 1000000);
for ($i = 0; $i < 32; $i++) {
$key .= substr($chars, (rand() % (strlen($chars))), 1);
}
break;
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
$key = '';
for ($i = 0; $i < 32; $i++) {
$key .= $chars[random_int(0, strlen($chars) - 1)];
}
return $key;
}