I am creating an ACME client and I need to find the modulus and exponent of my RSA public key, which I generate using the following code:
crypto.generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
I need the modulus and exponent, so that I can use them in the JWK section of my JWS:
alg: 'RS256',
jwk: {
kty: 'RSA',
e: '...',
n: '...'
},
nonce,
url: directory.newAccount
I have managed to decode the public key from base64 to hex using the following line, but I am not sure what to do next:
Buffer.from(publicKey, 'base64').toString('hex');
How do I find the modulus and exponent of an RSA public key in Node.js?
I have discovered that Node.js uses the public exponent 65537 by default: Node.js documentation.
It's easy as a piece of cake; it doesn't require 3rd party libraries
import { createPublicKey } from 'crypto'
const pemPublicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAphRAj+tRfbrYwnSFbWrj
...
vQIDAQAB
-----END PUBLIC KEY-----
`
const publicKey = createPublicKey(pemPublicKey)
console.log(publicKey.export({ format: 'jwk' }))
it will return object:
{
kty: 'RSA',
n: [modulus string],
e: [exponent string]
}