Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate persist and load keys using NodeJS?

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 image 624
Brian Avatar asked Sep 15 '25 14:09

Brian


1 Answers

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)

})()
like image 95
jean-smaug Avatar answered Sep 18 '25 08:09

jean-smaug