Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  135] [ 4]  / answers: 1 / hits: 5529  / 4 Years ago, wed, april 29, 2020, 12:00:00

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?






EDIT 1


I have discovered that Node.js uses the public exponent 65537 by default: Node.js documentation.


More From » node.js

 Answers
8

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]
}

[#3984] Monday, April 27, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
josefn questions
Sat, Mar 28, 20, 00:00, 4 Years ago
Fri, Feb 21, 20, 00:00, 4 Years ago
Wed, Oct 30, 19, 00:00, 5 Years ago
;