Example and documentation for crypto.DigestStream

It seems like I cannot post links, so trying to post without…

According to the changelog, the non-standard crypto.DigestStream interface is available in workers since December 2021:

  • crypto.DigestStream is a non-standard extension to the crypto API that supports generating a hash digest from streaming data. The DigestStream itself is a WritableStream that does not retain the data written into it; instead, it generates a digest hash automatically when the flow of data has ended. The same hash algorithms supported by crypto.subtle.digest() are supported by the crypto.DigestStream.

The types might be incomplete in @cloudflare/workers-types, not sure as the issue #198 on GitHub isn’t closed yet.

After some struggles with unclear 500 errors, I would highly appreciate a full example on digesting an incoming request.body via streams :slightly_smiling_face:

Any updates or suggestions?

It’s there.

export default {
  async fetch(req) {
    const digestStream = new crypto.DigestStream('SHA-256')

    await req.body.pipeTo(digestStream)
    const digest = await digestStream.digest;

    const hexString = [...new Uint8Array(digest)]
        .map (b => b.toString(16).padStart(2, "0"))
        .join ("");

    return new Response(hexString);

This will return the SHA-256 digest of the request body.

➜  ~ curl -X POST https://flat-scene-ebda.kianorguk.workers.dev/ --data 'aaa'
➜  ~ printf %s aaa | openssl dgst -sha256
1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.