0

Here:

const fs = require("fs").promises;
const { subtle } = require("crypto");
const getPem = require("rsa-pem-from-mod-exp");

async function createPub() {
  const keyPair = await subtle.generateKey({
    name: "RSASSA-PKCS1-v1_5",
    modulusLength: 4096,
    publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
    hash: "SHA-256"
    //works if and only if "sign" and "verify" is supplied
  }, true, ["sign", "verify", "encrypt", "decrypt"]);
  const key = await subtle.exportKey("jwk", keyPair.publicKey);
  fs.writeFile("public.key", getPem(key.n, key.e));
}
createPub();

throws

node:internal/per_context/domexception:53
    ErrorCaptureStackTrace(this);
    ^
DOMException [SyntaxError]: Unsupported key usage for a RSA key
    at new DOMException (node:internal/per_context/domexception:53:5)
    at __node_internal_ (node:internal/util:501:10)
    at Object.rsaKeyGenerate (node:internal/crypto/rsa:170:15)
    at SubtleCrypto.generateKey (node:internal/crypto/webcrypto:102:10)
    at createPub (/home/shepherd/Desktop/test/express/crypto/c.js:6:32)
    at Object.<anonymous> (/home/shepherd/Desktop/test/express/crypto/c.js:16:1)
    at Module._compile (node:internal/modules/cjs/loader:1120:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)
    at Module.load (node:internal/modules/cjs/loader:998:32)
    at Module._load (node:internal/modules/cjs/loader:839:12)

Node.js v18.6.0

Now I know that you usually use JWK to sign/verify your JWT, but why could you not also encrypt/decrypt some messages? Or is the primitive operation of exporting key only possible if my desired operation with that key is signing/verification? Nothing else? How should I interpret this error?

jps
  • 20,041
  • 15
  • 75
  • 79
milanHrabos
  • 2,010
  • 3
  • 11
  • 45
  • `RSASSA-PKCS1-v1_5` is a signature scheme, therefore such keys cannot be used for general encryption/decryption. `RSA-OAEP` is the only supported RSA-based encryption system. See: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt#parameters – Iridium Jul 18 '22 at 19:44
  • 2
    Actually, an RSA key pair can be used for both encryption and signing. This is not possible with the WebCrypto API, because it is a peculiarity of the WebCrypto API to bind the usage to the key, and signing/verifying and encrypting/decrypting apply mutually exclusive padding variants. If you don't want this restriction, you can use the [crypto](https://nodejs.org/api/crypto.html) module of NodeJS (with regard to the NodeJS tag). – Topaco Jul 18 '22 at 20:40

0 Answers0