Web Crypto Export JWK Not Working

I was attempting to create a new signing key and exporting it to a JWK, however, when I run the exportKey function I get the following error: “Asymmetric private key export requires pcks8 format.”

Whenever I run the same code using nodejs crypto.webcrypto it works as expected so I assume it has something to do with Cloudflares implementation causing this error.

The code:

const { privateKey } = await crypto.subtle.generateKey(
        name: 'RSASSA-PKCS1-v1_5',
        modulusLength: 4096,
        publicExponent: new Uint8Array([1, 0, 1]),
        hash: 'SHA-256'
    ['sign', 'verify']

const JWK = await crypto.subtle.exportKey('jwk', privateKey)

It’s absolutely working, but you’ll have to convert keys into their correct format. WebCrypto API doesn’t work the same way that NodeJS crypto does.

There’s some examples here:

I am fully aware that NodeJS crypto does not work the same. As I said though I was using their webcypto implementation which mimics the web version of crypto. Cloudflare’s implementation for crypto seems to actually be incorrect. If you look at the MDN documentation they link to SubtleCrypto.generateKey() - Web APIs | MDN (mozilla.org) it shows the code that I have. However, for Cloudflare’s implementation to work you must specify hash as an object with a key name for the hash function to use. (Or the MDN has their documentation wrong).

Thanks though as I did get it working now with the small change to generateKey.

If you have any more issues I would recommend joining the official Workers discord server

I am in the discord no one answered this question from there that’s why I posted it here.