Skip to content

Commit

Permalink
Polished secure random number implementation (#191285)
Browse files Browse the repository at this point in the history
## Summary

Polished secure random number implementation.

---------

Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
elena-shostak and elasticmachine authored Aug 28, 2024
1 parent ecec57c commit 1344d3b
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/plugins/interactive_setup/server/verification_code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit 1344d3b

Please sign in to comment.