TIL the WebCrypto API
POSTED ON:
TAGS: javascript mdn math
Is Crypto API the same as Math.random()
?
If you dealing with sensitive applications and need a more secure method of randomization, I’d recommend the Crypto API. Reasons you may want to use WebCrypto include temporary verification codes, random password generation, randomized lottery numbers, etc.
If you need randomization for the purposes of cybersecurity, cryptography, or statistics, use the function window.crypto.getRandomValues
Heck, the MDN for Math.random() even says it: "... does not provide cryptographically secure random numbers. Do not use them for anything related to security."
Via this John Deters on StackExchange.)
Math.random is designed for statistical simulations; and the numbers it produces are supposed to be randomly scattered around the number space. However, it is not designed to produce "unguessable" numbers, only numbers that are good for statistics. In other words, it doesn't matter in a simulation if your numbers have some internal pattern, or if you can repeat the random sequence.
The Crypto library, on the other hand, is designed to give numbers that are unguessable. They are not just random, but they have no identifiable relationship to each other. Learning a million random numbers output by it still won't reveal an inner pattern that helps you guess the next random value.
Crypto.getRandomValues()
Fills the passed TypedArray with cryptographically sound random values.
Crypto.randomUUID()
Returns a randomly generated, 36 character long v4 UUID.
Usage notes
Related TILs
Tagged: javascript