← Lessons

quiz vs the machine

Platinum1780

Frontend

The Web Crypto API

Hash, encrypt, and generate secure randomness natively in the browser.

6 min read · advanced · beat Platinum to climb

Cryptography done right

The Web Crypto API, reached through crypto subtle, provides low level cryptographic primitives implemented natively rather than in slow, error prone JavaScript.

  • digest computes hashes like SHA two five six
  • generateKey creates symmetric or asymmetric keys
  • encrypt and decrypt handle confidentiality
  • sign and verify handle authenticity
  • Most methods are promise based and operate on ArrayBuffers

Secure randomness

For random values, crypto getRandomValues fills a typed array with cryptographically strong random numbers. Never use Math random for security, since it is predictable.

Key handling rules

Keys are CryptoKey objects with explicit usages and an extractable flag. A non extractable key cannot be read out as raw bytes, which limits exposure even if scripts are compromised.

A caution

Web Crypto gives strong primitives, but using them correctly still requires care. Choosing modes, nonces, and key lengths wrongly can undermine security even with a correct implementation.

Key idea

The Web Crypto subtle interface offers native hashing, encryption, and signing on ArrayBuffers, while getRandomValues supplies secure randomness that Math random cannot.

Check yourself

Answer to earn rating on the learn ladder.

1. Why should you use crypto getRandomValues instead of Math random for security?

2. What does a non extractable CryptoKey prevent?

3. Which method of crypto subtle computes a hash like SHA two five six?