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);
})();