首页 > 解决方案 > 错误:EVP_PKEY_sign_init:此键类型不支持操作

问题描述

使用jsonwebtoken 8.2.0,以下代码使用 RS256 对有效负载进行签名:

const jwt = require('jsonwebtoken');
const token = jwt.sign(  //<<==sign throw error below
    {
      uid: this.id, //<<==payload
    },
    key,  //<<==RSA private key of 2048bit
    {
      expiresIn: (parseInt(process.env.jwt_token_expire_days) * 24).toString() + 'h',
      algorithm: 'RS256'
    }
  );

标志抛出错误:

(node:6528) UnhandledPromiseRejectionWarning: Error: error:0608D096:digital envelope routines:EVP_PKEY_sign_init:operation not supported for this keytype
    at Sign.sign (internal/crypto/sig.js:110:29)
    at Object.sign (C:\d\code\js\xyz\node_modules\jwa\index.js:152:45)
    at Object.jwsSign [as sign] (C:\d\code\js\xyz\node_modules\jws\lib\sign-stream.js:32:24)
    at Object.module.exports [as sign] (C:\d\code\js\xyz\node_modules\jsonwebtoken\sign.js:204:16)
    at Viewer.RSAAuthToken (C:\d\code\js\xyz\models\viewer.js:162:21)
    at C:\d\code\js\xyz\routes\viewers.js:184:41
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6528) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6528) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Viewer verification status update failed TypeError: res.setheader is not a function
    at C:\d\code\js\xyz\routes\viewers.js:203:17
    at processTicksAndRejections (internal/process/task_queues.js:93:5)

RSA 私钥(2048 位)如下所示:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAtBwLxqZEirr0uhtMTThmVDu3XKFVgE+qQqQ6oi6P/cvnTBHc
zlnmgqYNpufUbnIgGSZ9RzL29gVq6o/Dc4Sf1C0sEdkU1A5weFEegpeQTfEU1XI9
.....
0q6yoDXSl7JC+y5BWaz75xFX+tb4hKVTD27BvNDYRuvRsFeiKnn7vDmVS1/CoSnd
bv9Y1DrudRU2PkgAUPqbxDzuCNY9VW8IAP/DCw0oJBJP+wzdH9uvhg==
-----END RSA PRIVATE KEY-----

这里有什么问题?

标签: jwt

解决方案


这可能是因为您的 RSA 密钥实际上是 RSA-PSS 密钥,对使用的填充、使用、算法、摘要或这些的任何组合有限制。您可以通过执行来确认这个假设

const { createPrivateKey } = require('crypto')

const pk = createPrivateKey(pem)

console.log(pk.asymmetricKeyType)

如果您被rsa-pss登录,那么您的密钥将限制可以使用它执行的操作。


推荐阅读