Solving buffer.readUIntBE is not a function reading a JWKS key with NodeRSA

Recently while trying to read a public key in from a JWKS endpoint I was stumped by an error when importing the public key using [NodeRSA](https://github.com/rzcoder/node-rsa). My code looked like this:

```Typescript
  return rsa.importKey(
    {
      n: Buffer.from(jwksKey.n),
      e: jwksKey.e,
    },
    "components-public"
  );
```

The error was:

```bash
TypeError: buffer.readUIntBE is not a function
    at Object.module.exports.get32IntFromBuffer (C:\dev\jwttest\node_modules\node-rsa\src\utils.js:43:27)
    at RSAKey.module.exports.Key.RSAKey.setPublic (C:\dev\jwttest\node_modules\node-rsa\src\libs\rsa.js:172:48)
    at Object.publicImport (C:\dev\jwttest\node_modules\node-rsa\src\formats\components.js:44:17)
    at Object.detectAndImport (C:\dev\jwttest\node_modules\node-rsa\src\formats\formats.js:65:48)
    at NodeRSA.module.exports.NodeRSA.importKey (C:\dev\jwttest\node_modules\node-rsa\src\NodeRSA.js:183:22)
    at C:\dev\jwttest\dist\jwks.js:53:20
    at Generator.next ()
    at fulfilled (C:\dev\jwttest\dist\jwks.js:5:58)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
```

I couldn't see any issue with the way I was setting up the buffer. I was able to log the contents out. Everything looked correct. When I searched for `buffer.readUIntBE is not a function` I found nothing useful. It left my scratching my head and saying "What the damn hell!?".



Eventually I worked it out. The issue wasn't with th buffer I had so much as the one I didn't. I had been let down by own poor use of the Typescript type system. I had assumed that since the code was compiling that I was passing correct values and skipping reading the documentation. The mistake I had made was that the JWKS spec sets up the [`e` (Exponent) parameter](https://tools.ietf.org/html/rfc7518#section-6.3.1.2) as a Base64urlUInt-encoded string value and the `new NodeRSA().importKey({n,e}, "public-components")` api takes a `number`or a `Buffer` as the `n` parameter.  

In this case the error I was saying that `buffer.readUIntBE is not a function` where `buffer` is a `string` not a `Buffer` 

Comments

Popular posts from this blog

Testing functions that use local storage with Jest

Solving `Empty reply from server` in DotNet Core

Can't resolve DNS Aws