INTEGRITY Cloudflare Docs

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 signing requests.


Constructors

Parameters

Usage

export default {
  async fetch(req) {
    // Fetch from origin
    const res = await fetch(req);

    // We need to read the body twice so we `tee` it (get two instances)
    const [bodyOne, bodyTwo] = res.body.tee();
    // Make a new response so we can set the headers (responses from `fetch` are immutable)
    const newRes = new Response(bodyOne, res);
    // Create a SHA-256 digest stream and pipe the body into it
    const digestStream = new crypto.DigestStream("SHA-256");
    bodyTwo.pipeTo(digestStream);
    // Get the final result
    const digest = await digestStream.digest;
    // Turn it into a hex string
    const hexString = [...new Uint8Array(digest)]
      .map(b => b.toString(16).padStart(2, '0'))
      .join('')
    // Set a header with the SHA-256 hash and return the response
    newRes.headers.set("x-content-digest", `SHA-256=${hexString}`);
    return newRes;
  }
}
export default {
  async fetch(req): Promise<Response> {
    // Fetch from origin
    const res = await fetch(req);

    // We need to read the body twice so we `tee` it (get two instances)
    const [bodyOne, bodyTwo] = res.body.tee();
    // Make a new response so we can set the headers (responses from `fetch` are immutable)
    const newRes = new Response(bodyOne, res);
    // Create a SHA-256 digest stream and pipe the body into it
    const digestStream = new crypto.DigestStream("SHA-256");
    bodyTwo.pipeTo(digestStream);
    // Get the final result
    const digest = await digestStream.digest;
    // Turn it into a hex string
    const hexString = [...new Uint8Array(digest)]
      .map(b => b.toString(16).padStart(2, '0'))
      .join('')
    // Set a header with the SHA-256 hash and return the response
    newRes.headers.set("x-content-digest", `SHA-256=${hexString}`);
    return newRes;
  }
} satisfies ExportedHandler;

Methods

Parameters

SubtleCrypto Methods

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

encrypt

Parameters

decrypt

Parameters

sign

Parameters

verify

Parameters

digest

Parameters

generateKey

Parameters

deriveKey

Parameters

deriveBits

Parameters

importKey

Parameters

exportKey

Parameters

wrapKey

Parameters

unwrapKey

Parameters

timingSafeEqual

Parameters

Supported algorithms

Workers implements all operations of the WebCrypto standard, as shown in the following table.

A checkmark (✓) indicates that this feature is believed to be fully supported according to the spec.
An x (✘) indicates that this feature is part of the specification but not implemented.
If a feature only implements the operation partially, details are listed.

Algorithm sign()
verify()
encrypt()
decrypt()
digest() deriveBits()
deriveKey()
generateKey() wrapKey()
unwrapKey()
exportKey() importKey()
RSASSA PKCS1 v1.5
RSA PSS
RSA OAEP
ECDSA
ECDH
Ed255191
X255191
NODE ED255192
AES CTR
AES CBC
AES GCM
AES KW
HMAC
SHA 1
SHA 256
SHA 384
SHA 512
MD53
HKDF
PBKDF2

Footnotes:

  1. Algorithms as specified in the Secure Curves API.

  2. Legacy non-standard EdDSA is supported for the Ed25519 curve in addition to the Secure Curves version. Since this algorithm is non-standard, note the following while using it:

    • Use NODE-ED25519 as the algorithm and namedCurve parameters.
    • Unlike NodeJS, Cloudflare will not support raw import of private keys.
    • The algorithm implementation may change over time. While Cloudflare cannot guarantee it at this time, Cloudflare will strive to maintain backward compatibility and compatibility with NodeJS's behavior. Any notable compatibility notes will be communicated in release notes and via this developer documentation.
  3. 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.