Polished secure random number implementation (#191285)

## Summary

Polished secure random number implementation.

---------

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
This commit is contained in:
elena-shostak 2024-08-28 13:05:54 +02:00 committed by GitHub
parent ecec57ca52
commit 1344d3b238
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -69,20 +69,24 @@ Your verification code is: ${highlightedCode}
/**
* Returns a cryptographically secure and random 6-digit code.
*
* Implementation notes: `secureRandomNumber` returns a random number like `0.05505769583xxxx`. To
* turn that into a 6 digit code we multiply it by `10^6` and result is `055057`.
*/
private static generate(length: number) {
return Math.floor(secureRandomNumber() * Math.pow(10, length))
.toString()
.padStart(length, '0');
return secureRandomNumber(length).join('');
}
}
/**
* Cryptographically secure equivalent of `Math.random()`.
*/
function secureRandomNumber() {
return crypto.randomBytes(4).readUInt32LE() / 0x100000000;
function secureRandomNumber(length: number) {
const digits = [];
while (digits.length < length) {
const byte = crypto.randomBytes(1)[0];
if (byte >= 250) {
continue;
}
digits.push(byte % 10);
}
return digits;
}