gpt4 book ai didi

javascript - 将 cryto.generateKeyPair 与 jsonwebtoken 一起使用

转载 作者:行者123 更新时间:2023-11-29 23:04:45 25 4
gpt4 key购买 nike

在 Node 10 中有一个新方法 generateKeyPair,我是这样使用的:

const { publicKey, privateKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 4096,
publicKeyEncoding: {
type: "spki",
format: "pem"
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
cipher: "aes-256-cbc",
passphrase: "top secret"
}
});

我现在正尝试使用此私钥从 jsonwebtoken 创建一个 jwt:

function createJWT(id) {
return new Promise((resolve, reject) => {
jwt.sign(
{ id: id + "" },
privateKey,
{ algorithm: "RS256", expiresIn: "2h" },
(err, token) => {
if (err) reject(err);
resolve(token);
}
);
});
}

不幸的是,这似乎不起作用:

Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
at Sign.sign (internal/crypto/sig.js:83:26)
at Object.sign (/Users/francoisbillioud/Documents/Tests/SimpleQL/node_modules/jwa/index.js:76:45)
at jwsSign (/Users/francoisbillioud/Documents/Tests/SimpleQL/node_modules/jws/lib/sign-stream.js:32:24)
at SignStream.sign (/Users/francoisbillioud/Documents/Tests/SimpleQL/node_modules/jws/lib/sign-stream.js:58:21)
at SignStream.<anonymous> (/Users/francoisbillioud/Documents/Tests/SimpleQL/node_modules/jws/lib/sign-stream.js:46:12)
at Object.onceWrapper (events.js:273:13)
at DataStream.emit (events.js:182:13)
at DataStream.<anonymous> (/Users/francoisbillioud/Documents/Tests/SimpleQL/node_modules/jws/lib/data-stream.js:32:12)
at process._tickCallback (internal/process/next_tick.js:61:11)

可以看看here .

我错过了什么?

最佳答案

通过提供密码和密码短语,私钥将根据 documentation 使用基于 PKCS#5 v2.0 密码的加密进行加密。 . jsonwebtoken 模块声明如下:

In case of a private key with passphrase an object { key, passphrase } can be used (based on crypto documentation), in this case be sure you pass the algorithm option.

如果您确实需要加密私钥,则需要保存私钥加密生成中使用的密码,并在您的 sign() 函数中提供它。

let passphrase = 'top secret'

const { privateKey } = crypto.generateKeyPairSync("rsa", {
modulusLength: 4096,
publicKeyEncoding: {
type: "spki",
format: "pem"
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
cipher: "aes-256-cbc",
passphrase
}
});

function createJWT(id) {
return new Promise((resolve, reject) => {
jwt.sign(
{
id: id + ""
},
{
key: privateKey,
passphrase
},
{
algorithm: "RS256",
expiresIn: "2h"
},
(err, token) => {
if (err) reject(err);
resolve(token);
}
);
});
}

关于javascript - 将 cryto.generateKeyPair 与 jsonwebtoken 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54980947/

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