Generating Secure Random Numbers in TypeScript

submited by
Style Pass
2023-11-21 01:00:03

To understand how secure random number generation works in TS, you first have to understand how JavaScript’s typed arrays work. Typed arrays are objects that store binary data as arrays of numbers. The capacity of a typed array is measured in bits.

Bits are binary, meaning they can be in one of two states (0 or 1). A single bit therefore has a capacity of 2**1, which is of course equal to 2. Every time you add a bit, you’re multiplying the capacity by two. Two bits can therefore store 2**2 numbers, because they can be in any of four states (00, 11, 01, and 10).

The JS specification includes several unsigned typed arrays (unsigned meaning all of the numbers are positive, and therefore don’t require a negative or positive sign to differentiate them).

For the purpose of simplicity we’ll assume that the minimum, maximum, and range of the set of random numbers we’re generating are all numbers (rather than bigints), and that the range fits in a 32 bit array. In practice, I’ve rarely found myself needing random numbers that don’t satisfy these requirements.

Leave a Comment