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