mirror of
https://github.com/elastic/kibana.git
synced 2025-04-24 09:48:58 -04:00
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:
parent
ecec57ca52
commit
1344d3b238
1 changed files with 12 additions and 8 deletions
|
@ -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;
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue