I've been learning NodeJS and the crypto library. Specifically, I'd like to generate a signature and then verify it. I have working code for this below. The NodeJS Crypto library docs were adequate to figure this much out. I can also export those keys as PEM, so I can just save to disk using fs.writeFile. But I've run into a wall finding documentation and/or examples of how to load the PEM keys back again. How would I go about saving the keys so that I can load them to validate the signature at a later date? Is there a built in method, or should I just save the PEM and then load it later. And after loading the PEM how would I use the crypto library to convert the PEM string back into an actual crypto.KeyObject?
const crypto = require('crypto');
(async () => {
    const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
        //The standard secure default length for RSA keys is 2048 bits
        modulusLength: 2048,
    });
    let data = "Signing Data";
    const signature = crypto.sign("sha256", Buffer.from(data), {
        key: privateKey,
        padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
    });
    console.log(signature.toString("base64"))
    const isVerified = crypto.verify(
        "sha256",
        Buffer.from(data),
        {
            key: publicKey,
            padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
        },
        signature
    )
    console.log("signature verified: ", isVerified);
})();
Like you said you can use writeFile to save your keys and after that you can use readFile to get them back.
Also, you should use require("fs/promises") instead of require("fs") since you're using an async auto-invoked function.
const fs = require("fs/promises")
const KEY_FILE_PATH = `${__dirname}/MY_KEY`
(async () => {
  const privateKey = "..."
  
  await fs.writeFile(KEY_FILE_PATH, privateKey)
  // Later
  const key = await fs.readFile(KEY_FILE_PATH)
})()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With