Why I am this Error in decoding JSON Web Token Error: error:0909006C:PEM routines:get_name:no start line

Why I am this Error in decoding JSON Web Token Error: error:0909006C:PEM routines:get_name:no start line

我有一个名为 social-public.key 的密钥,我用它来解码 JWT,但问题是我遇到如下错误

Error occurred while decoding access token Error: error:0909006C:PEM routines:get_name:no start line
    at Verify.verify (internal/crypto/sig.js:157:24)
    at Object.verify (D:\SocialAnalysisDashboard\social-dashboard-user-service\node_modules\jwa\index.js:164:21)
    at Object.jwsVerify [as verify] (D:\SocialAnalysisDashboard\social-dashboard-user-service\node_modules\jws\lib\verify-stream.js:54:15)
    at D:\SocialAnalysisDashboard\social-dashboard-user-service\node_modules\jsonwebtoken\verify.js:127:19
    at getSecret (D:\SocialAnalysisDashboard\social-dashboard-user-service\node_modules\jsonwebtoken\verify.js:90:14)
    at Object.module.exports [as verify] (D:\SocialAnalysisDashboard\social-dashboard-user-service\node_modules\jsonwebtoken\verify.js:94:10)
    at D:\SocialAnalysisDashboard\social-dashboard-user-service\express\Middlewares\auth.js:24:46
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  library: 'PEM routines',
  function: 'get_name',
  reason: 'no start line',
  code: 'ERR_OSSL_PEM_NO_START_LINE'
}

这是我用来解码 JWT 的代码,

const decodedToken = jwt.verify(token, key, {algorithms: ['RS256']});

我找到的大多数解决方案都与 .pem 个文件有关。

我遇到了类似的问题,我在 this 问题 post 的帮助下修复了它。如果您使用 HS256,您只需要一个密钥来签名和验证。 RSA 版本需要 public 和私钥(Public 用于验证,私有用于签名)

按照以下步骤操作:

  1. 拥有有效的 public 及其关联的私钥。 (csfieldguide, travistidwell)
  2. 包括'---private/public键开始---'和'---public/private键结束---'部分
  3. 我将其保存在 base64 中,可以直接在 npm
  4. jsonwebtoken 模块中提供
  5. 确保换行字节 (\n) 与 base64 字符串一起给出

示例:

let secret = [
        '-----BEGIN PRIVATE KEY-----',
        'MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAkcd7iupXSHhgIRat',
        'b2gnEiyC3AIf7GCrISTtgM5Lb8kccGjunU8sIqwwd3BV6qD+pExeyvMyU085RHRX',
        'ud1cyQIDAQABAkAzmni6GPAiwDHPJLbqK+VAwq7j8ICabTHGvsqwANalT/O4V75m',
        'e2ExeqV05+jlzVOGrQ953n8Mx1u0uRgPlfoBAiEAyO3qytGKRRzlqBuGwPFPde4a',
        '66ZW4AmRcBwwuKp1zgkCIQC5u/2j/JFzM4GTbpoC0a2u78+tqYQW7Y/Usu6AAubI',
        'wQIhAMKbhMQJ7UUBNwH6HyryzcZn5pUEl7IIMmAGPb4uA0mZAiAbJPhawQzY00w6',
        'qc1kYBSMHowxiza8yxdcNJJarxHfgQIgcw2oEtn8GbvNMOsFg0Q9TPMdQ+uhxhWK',
        'xhVgWkIkTVU=',
        '-----END PRIVATE KEY-----',
    ].join('\n');

验证时 public 密钥也是如此。

// Create a signed JWT token
const token = jwt.sign(payload, privKey, {algorithm: 'RS256', ...otherSignOptions}); 

// returns undefined if token could not be verified
jwt.verify(token, pubKey);

我当然建议从文件中读取密钥而不是对其进行硬编码。 (最好在安全的地方)