Using python to generate a JWT raises ValueError "Could not deserialize key data"

问题描述 投票:0回答:0

我正在尝试按照这些说明为 Github 应用生成 JWT https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a- json-web-token-jwt-for-a-github-app

这就是我所做的:

安装 Python3

pip3 安装 jwt

我创建了一个具有 RSA 私钥的 pem 文件

我从上面的链接复制了代码并创建了一个 get-jwt.py 文件:

#!/usr/bin/env python3
import jwt
import time
import sys

# Get PEM file path
if len(sys.argv) > 1:
    pem = sys.argv[1]
else:
    pem = input("Enter path of private PEM file: ")

# Get the App ID
if len(sys.argv) > 2:
    app_id = sys.argv[2]
else:
    app_id = input("Enter your APP ID: ")

# Open PEM
with open(pem, 'rb') as pem_file:
    signing_key = jwt.jwk_from_pem(pem_file.read())

payload = {
    # Issued at time
    'iat': int(time.time()),
    # JWT expiration time (10 minutes maximum)
    'exp': int(time.time()) + 600,
    # GitHub App's identifier
    'iss': app_id
}

# Create JWT
jwt_instance = jwt.JWT()
encoded_jwt = jwt_instance.encode(payload, signing_key, alg='RS256')

print(f"JWT:  ", encoded_jwt)

当我做

python3 get-jwt.py
时,我得到以下错误:

Traceback (most recent call last):
  File "/Users/al/Library/Python/3.9/lib/python/site-packages/jwt/jwk.py", line 345, in jwk_from_private_bytes
    privkey = private_loader(content, password, backend)  # type: ignore[operator]  # noqa: E501
  File "/Users/al/Library/Python/3.9/lib/python/site-packages/cryptography/hazmat/primitives/serialization/base.py", line 24, in load_pem_private_key
    return ossl.load_pem_private_key(
  File "/Users/al/Library/Python/3.9/lib/python/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 957, in load_pem_private_key
    return self._load_key(
  File "/Users/al/Library/Python/3.9/lib/python/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1152, in _load_key
    self._handle_key_loading_error()
  File "/Users/al/Library/Python/3.9/lib/python/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 1207, in _handle_key_loading_error
    raise ValueError(
ValueError: ('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [<OpenSSLError(code=503841036, lib=60, reason=524556, reason_text=unsupported)>])

我做错了什么?

python python-3.x jwt
© www.soinside.com 2019 - 2024. All rights reserved.