gpt4 book ai didi

node.js - 如何使用 node.js 加密将公钥和私钥保存到文件?

转载 作者:行者123 更新时间:2023-12-05 04:48:28 24 4
gpt4 key购买 nike

在 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

有人知道吗?

谢谢

最佳答案

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

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

他所做的是调整 key 对生成器的配置,尽管在某些情况下此解决方案可能无法解决问题(例如 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("====================================");

希望对大家有所帮助

关于node.js - 如何使用 node.js 加密将公钥和私钥保存到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68074517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com