结合使用cryto.generateKeyPair和jsonwebtoken

时间:2019-03-04 10:10:18

标签: javascript node.js jwt

在节点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"
  }
});

我现在正在尝试使用此privateKey从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

我想念什么?

1 个答案:

答案 0 :(得分:1)

通过提供密码和密码短语,私钥将根据documentation使用基于PKCS#5 v2.0密码的加密方式进行加密。 jsonwebtoken模块规定以下内容:

  

如果带有密码短语的私钥是一个对象{密钥,密码短语}   可以使用(基于加密文档),在这种情况下,请确保您   通过算法选项。

如果您确实需要加密私钥,则需要保存私钥的加密生成中使用的密码,并将其提供给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);
      }
    );
  });
}