Today I Learned - Rocky Kev

TIL the WebCrypto API

POSTED ON:

TAGS:

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

MDN - WebCrypto


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.