2

I am using pyjwt library for generate a JWT token. I got this error when I am encoding. I put the code that I use to encode below. Does anyone know why it doesn't allow me to encode correctly?

CODE:

import datetime
import jwt

PROJECT_ID = 'test-iot-core-278019'
SSL_PRIVATE_KEY_FILEPATH = 'roots.pem'
SSL_ALGORITHM = 'ES256'

def create_jwt(project_id, private_key_file, algorithm):
    token = {
        'iat': datetime.datetime.utcnow(),
        'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
        'aud': project_id
    }
    with open(private_key_file, 'r') as f:
        private_key = f.read()

    print('Creating JWT using {} from private key file {}'.format(algorithm, private_key_file))
    return jwt.encode(token, private_key, algorithm=algorithm)

print('JWT token:')
print(create_jwt(PROJECT_ID, SSL_PRIVATE_KEY_FILEPATH, SSL_ALGORITHM))

ERROR:

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/project/project.py", line 28, 
in <module>
    print(create_jwt(PROJECT_ID, SSL_PRIVATE_KEY_FILEPATH, SSL_ALGORITHM))
  File "C:/Users/User/PycharmProjects/project/project.py", line 24, 
in create_jwt
    return jwt.encode(token, private_key, algorithm=algorithm)
  File "C:\Users\User\PycharmProjects\project\venv\lib\site- 
packages\jwt\api_jwt.py", line 65, in encode
    json_payload, key, algorithm, headers, json_encoder
  File "C:\Users\User\PycharmProjects\project\venv\lib\site- 
packages\jwt\api_jws.py", line 113, in encode
    key = alg_obj.prepare_key(key)
  File "C:\Users\User\PycharmProjects\project\venv\lib\site- 
packages\jwt\algorithms.py", line 351, in prepare_key
    key = load_pem_private_key(key, password=None, backend=default_backend())
  File "C:\Users\User\PycharmProjects\project\venv\lib\site- 
packages\cryptography\hazmat\primitives\serialization\base.py", line 16, in 
load_pem_private_key
    return backend.load_pem_private_key(data, password)
  File "C:\Users\User\PycharmProjects\project\venv\lib\site- 
packages\cryptography\hazmat\backends\openssl\backend.py", line 1382, in 
_handle_key_loading_error
    raise ValueError("Could not deserialize key data.")
ValueError: Could not deserialize key data.
Saul JP
  • 325
  • 2
  • 11

0 Answers0