node.jscryptographynode-forge

How do I verify a key pair matches? (node-forge)


I need to make sure a client generated RSA key pair matches before signing it. I can't seem to find any documentation (npm:node-forge) on how to do so. I'm guessing I could sign something with it, and then verify the signature, but that's not efficient. I currently have this:

const Forge = require("node-forge");

try {
    publicKey = Forge.pki.publicKeyFromPem(publicKey);
    privateKey = Forge.pki.privateKeyFromPem(privateKey);
} catch(err) {
    // ...
}

// ...

Any ideas are appreciated.


Solution

  • I've found my answer: I don't need to be sent the public key in the first place. You can build the public key from the private key like this:

    // const privateKey = ...;
    const publicKey = Forge.pki.setRsaPublicKey(privateKey.n, privateKey.e);
    

    More information on this solution can be found here: Extract public key from private key pem using only nodejs/javascript.