Web Crypto API

Also known as: Web Cryptography API · SubtleCrypto

On this page 7

The Web Crypto API, formally the Web Cryptography API, is the browser interface that gives JavaScript access to native cryptographic primitives: secure random numbers, hashing, symmetric and asymmetric encryption, digital signatures, key derivation and key management. Among Web APIs, it is the standard way to perform cryptography in browsers, workers and server runtimes such as Node.js and Deno.

Published as a W3C Recommendation in 2017, the API is exposed through the global crypto object, whose subtle property holds the SubtleCrypto interface. Operations run in audited native code rather than in JavaScript libraries, and keys can be marked so that script can never read the raw key material.

How the Web Crypto API is structured

The Web Crypto API has two layers: a small set of synchronous helpers on crypto and the asynchronous SubtleCrypto interface on crypto.subtle. The helpers getRandomValues() and randomUUID() produce cryptographically secure randomness, while SubtleCrypto methods return Promises and operate on CryptoKey objects.

A CryptoKey carries its algorithm, its permitted key usages such as encrypt or sign, and an extractable flag. When extractable is false, the browser refuses to export the key, so even code with full page access can use the key but cannot copy its bytes. SubtleCrypto is available only in secure contexts, meaning HTTPS pages or localhost.

The following table lists the main SubtleCrypto operations and what each one produces.

MethodInputOutput
digestAlgorithm and dataHash as an ArrayBuffer
encrypt and decryptKey, algorithm parameters, dataCiphertext or plaintext
sign and verifyKey, data, signatureSignature or Boolean result
generateKeyAlgorithm and usagesCryptoKey or key pair
deriveKey and deriveBitsBase key and parametersDerived key or raw bits
importKey and exportKeyKey data and formatCryptoKey or exported key
wrapKey and unwrapKeyKey plus wrapping keyEncrypted key or CryptoKey
Core SubtleCrypto methods

Supported algorithms and key formats

The specification defines a fixed set of algorithms rather than an open plugin model, which keeps implementations consistent across browsers. Modern code should prefer AES-GCM, ECDSA, ECDH, HKDF and SHA-256 or stronger; older algorithms remain for interoperability.

PurposeAlgorithmsRecommendation
Symmetric encryptionAES-GCM, AES-CBC, AES-CTRAES-GCM for authenticated encryption
Key wrappingAES-KW, RSA-OAEPAES-KW for wrapping symmetric keys
SignaturesECDSA, RSA-PSS, RSASSA-PKCS1-v1_5, Ed25519ECDSA P-256 or Ed25519 where supported
Key agreementECDH, X25519ECDH followed by HKDF
HashingSHA-1, SHA-256, SHA-384, SHA-512Avoid SHA-1 for security uses
Key derivationHKDF, PBKDF2PBKDF2 only for passwords, high iterations
Message authenticationHMACHMAC with SHA-256
Algorithm families in the Web Crypto API

Keys move in and out of the API in four formats: raw bytes, PKCS #8, SPKI and JSON Web Key. JWK is convenient for exchange with web services, while SPKI and PKCS #8 match the formats used by OpenSSL and most server libraries. The Curve25519 algorithms Ed25519 and X25519 were added later, so their availability should be checked per browser version.

Web Crypto API compared with JavaScript libraries

The Web Crypto API replaces most pure JavaScript cryptography libraries for standard primitives. Native code is faster, resists timing attacks better and supports non-extractable keys, which no library can emulate because a library always holds keys in ordinary memory.

AspectWeb Crypto APIPure JavaScript library
PerformanceNative, often hardware acceleratedSlower, interpreted or JIT code
Key protectionNon-extractable CryptoKey objectsKeys always readable by script
Algorithm rangeFixed standard setAny algorithm the library adds
Bundle sizeZero, built into the platformAdds code to every page
StreamingWhole buffers onlyIncremental hashing often available
Native API versus library cryptography

Libraries remain useful for algorithms outside the standard, such as Argon2 password hashing or post-quantum schemes, and for incremental hashing of very large files. Good practice is to use native primitives wherever they exist and add a library only for the gap.

Practical use and secure configuration

Typical uses include end-to-end encrypted messaging, client-side encryption of files before upload, signing requests with device-bound keys and verifying data integrity. Non-extractable keys can be stored in IndexedDB as CryptoKey objects, which survive page reloads without ever exposing raw bytes.

  • Generate a fresh 96-bit IV for every AES-GCM encryption with getRandomValues() and never reuse it with the same key.
  • Derive keys from passwords with PBKDF2 and several hundred thousand iterations, plus a random salt per user.
  • Set extractable to false unless a key must be exported or wrapped.
  • Limit key usages to the minimum, for example sign only for a signing key.

Limitations and common mistakes

The Web Crypto API secures operations, not the code that calls them. If an attacker can inject script through XSS or alter the JavaScript served to the page, they can use non-extractable keys or read plaintext before encryption, so Content Security Policy and code integrity matter as much as the algorithm.

MistakeConsequenceFix
Reusing an AES-GCM IVLoss of confidentiality and integrityRandom IV per message
Using Math.random() for keysPredictable secretsUse crypto.getRandomValues()
Calling crypto.subtle over HTTPAPI undefined in insecure contextServe the page over HTTPS
Hashing passwords with SHA-256 aloneFast offline brute forceUse PBKDF2 or a dedicated hash
Frequent errors and their fixes

The API also offers no key storage, no certificate handling and no streaming encryption, so applications must design those parts themselves with care.

The short version

The Web Crypto API is a built-in toolbox for locking and checking data inside the browser. A website can use it to scramble a message for one reader. It can prove that a file is unchanged. It can also create truly unpredictable random numbers.

The tools are part of the browser itself, so they are fast and carefully tested. Think of a bank safe deposit box. The website can ask the box to lock or unlock something. Yet the key itself never leaves the box.

Where it makes a difference

A health clinic offers patients a web portal for uploading scanned documents. To limit exposure if the storage service is ever breached, the developers encrypt every file in the browser before upload with AES-GCM using a fresh random IV and a 256-bit key.

Each document key is wrapped with the patient’s key, derived with PBKDF2 from a passphrase using a per-user salt and 600,000 iterations, and stored only in wrapped form. The server therefore stores ciphertext it cannot read. When a storage bucket is later misconfigured and briefly exposed, the leaked files are unreadable, and the incident response focuses on configuration rather than patient notification of readable records.