【问题标题】:How to save public and private key to file using node.js crypto?如何使用 node.js 加密将公钥和私钥保存到文件中?
【发布时间】:2021-06-21 20:47:03
【问题描述】:

在 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

有人知道吗?

谢谢

【问题讨论】:

  • in the documentation for generateKeyPairSync 的示例向您展示了如何提供 publicKeyEncodingprivateKeyEncoding 选项以及为它们提供什么值。

标签: node.js file cryptography


【解决方案1】:

fs.writeFileSync 方法应该接受Buffer 对象,但generateKeyPairSync 方法可能输出strings。

解决此问题的一种方法是从您要写入的字符串创建Buffer。例如:

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

这是Buffer documentation的链接

【讨论】:

    【解决方案2】:

    很可能您已经找到了解决问题的方法,或者其他答案已经帮助您解决了问题,为了帮助可能面临相同问题的任何其他开发人员,这里有一篇文章,解决方案的功劳归于作者:

    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("====================================");
    

    希望这对某人有所帮助

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 2012-04-11
      • 1970-01-01
      • 2018-07-31
      • 2012-06-26
      • 1970-01-01
      相关资源
      最近更新 更多