如何使用Node.js的加密模块将公钥和私钥保存到文件中?

3
在node.js的加密模块中,我生成了一个公钥/私钥,但是如何将其保存到文件并从文件中加载回内存?目前我有以下代码:

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

但我收到了这个错误

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

有人知道吗?

谢谢


1
generateKeyPairSync 的文档中提供了一个示例,展示了如何提供 publicKeyEncodingprivateKeyEncoding 选项以及它们应该赋予的值。请参考文档 - President James K. Polk
2个回答

3
很可能您已经找到了解决问题的方法,或者其他答案已经帮助过您。为了帮助可能面临相同问题的其他开发人员,这里有一篇文章,解决方案的功劳归于作者:https://zachgollwitzer.com/posts/2019/public-key-crypto/。他所做的是调整密钥对生成器的配置,虽然在某些情况下,这种解决方案可能无法解决问题(例如generateKeyPairSync函数的配置与下面的函数冲突),但它仍然对我起作用了。
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("====================================");

希望这能帮助到某些人。

-1

fs.writeFileSync方法应该接受一个Buffer对象,但是generateKeyPairSync方法输出的可能是string

修复这个问题的一种方法是通过从要写入的字符串创建一个Buffer。例如:

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

这里是Buffer文档的链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接