Skip to content
Workers
Visit Workers on GitHub
Set theme to dark (⇧+D)

Web Crypto

Background

The Web Crypto API provides a set of low-level functions for common cryptographic tasks. The Workers Runtime implements the full surface of this API, but with some differences in the supported algorithms compared to those implemented in most browsers.

Performing cryptographic operations using the Web Crypto API is significantly faster than performing them purely in JavaScript. If you want to perform CPU-intensive cryptographic operations, you should consider using the Web Crypto API.

The Web Crypto API is implemented through the SubtleCrypto interface, accessible via the global crypto.subtle binding. A simple example of calculating a digest (also known as a hash) is:

const myText = new TextEncoder().encode("Hello world!")
const myDigest = await crypto.subtle.digest(  {    name: "SHA-256",  },  myText, // The data you want to hash as an ArrayBuffer)
console.log(new Uint8Array(myDigest))

Some common uses include:

Methods

  • crypto.getRandomValues(bufferArrayBuffer)Promise<ArrayBuffer>
    • Fills the passed ArrayBuffer with cryptographically sound random values.

SubtleCrypto Methods

These methods are all accessed via crypto.subtle, which is also documented in detail on MDN.

Supported algorithms

Workers implements a subset of the most common cryptographic algorithms, as shown in the following table. We are happy to add support for more algorithms — let us know about your use case.

Algorithmsign()
verify()
encrypt()
decrypt()
digest()deriveBits()
deriveKey()
generateKey()wrapKey()
unwrapKey()
exportKey()
RSASSA-PKCS1-v1_5
RSA-PSS
ECDSA
HMAC
AES-CBC
AES-GCM
SHA-1
SHA-256
SHA-384
SHA-512
MD51
PBKDF2

Footnotes:

  1. MD5 is not part of the WebCrypto standard, but is supported in Cloudflare Workers for interacting with legacy systems that require MD5. MD5 is considered a weak algorithm. Do not rely upon MD5 for security.

See also