refactor: optimize random byte generation for recovery and JWT secret functions

This commit is contained in:
shuaiplus
2026-03-12 01:59:28 +08:00
parent 3eb517a92f
commit 0bb1baf768
5 changed files with 25 additions and 22 deletions
+9 -2
View File
@@ -16,9 +16,16 @@ interface SettingsPageProps {
function randomBase32Secret(length: number): string {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
const random = crypto.getRandomValues(new Uint8Array(length));
let out = '';
for (const x of random) out += alphabet[x % alphabet.length];
const maxUnbiasedByte = Math.floor(256 / alphabet.length) * alphabet.length;
while (out.length < length) {
const random = crypto.getRandomValues(new Uint8Array(length));
for (const x of random) {
if (x >= maxUnbiasedByte) continue;
out += alphabet[x % alphabet.length];
if (out.length >= length) break;
}
}
return out;
}