omega
omega

Reputation: 43883

How to save public and private key to file using node.js crypto?

In node.js crypto module, I generate a public/private key, but how do I save it to a file and load it back into memory from file? So far I have this

https://nodejs.org/api/crypto.html

const crypto = require("crypto")
const fs = require('fs');

// The `generateKeyPairSync` method accepts two arguments:
// 1. The type ok keys we want, which in this case is "rsa"
// 2. An object with the properties of the key
const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
    // The standard secure default length for RSA keys is 2048 bits
    modulusLength: 2048,
})

fs.writeFileSync("public.pem", publicKey);
fs.writeFileSync("private.pem", privateKey);

But I get this error

TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of PublicKeyObject

Does anyone know?

Thanks

Upvotes: 3

Views: 8843

Answers (2)

Mehdi Amenein
Mehdi Amenein

Reputation: 1197

most likely you have already found a solution for your problem or the other answer already helped you out, for the sake helping any other developer who might face the same issue, here is an article and the credit of the solution goes to the writer of it:

https://zachgollwitzer.com/posts/2019/public-key-crypto/

What he has done, was tweaking the configuration of the key pair generator, and although in some cases this solution might not resolve the issue (like the time that configuration of generateKeyPairSync function is conflicting with the one below) it still worked for me:

const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: "pkcs1",
    format: "pem",
  },
  privateKeyEncoding: {
    type: "pkcs1",
    format: "pem",
  },
});

console.log("====================================");

fs.writeFileSync("public.pem", publicKey);
fs.writeFileSync("private.pem", privateKey);

console.log("====================================");

Hope this helps someone out

Upvotes: 3

Chris Gilardi
Chris Gilardi

Reputation: 1540

The fs.writeFileSync method should accept a Buffer object, but likely the generateKeyPairSync method outputs strings.

One way to fix this is by creating a Buffer from the string you want to write. For example:

fs.writeFileSync("public.pem", Buffer.from(publicKey));
fs.writeFileSync("private.pem", Buffer.from(privateKey));

Here is the link to the Buffer documentation

Upvotes: -1

Related Questions