Using the EdDSA algorithm with PyJWT

615 Views Asked by At

I am trying to use the EdDSA algorithm for encoding but I keep getting the below error.

Any ideas as to what I am doing wrong?

EllipticCurvePrivateKey = "-----BEGIN PRIVATE KEY-----\[HIDDEN]\n-----END PRIVATE KEY-----"

encoded = jwt.encode({"some": "payload"}, EllipticCurvePrivateKey, 'EdDSA')

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/rogermukai/Dev/Templates/jwt-example/.venv/lib/python3.10/site-packages/jwt/api_jwt.py", line 67, in encode
    return api_jws.encode(json_payload, key, algorithm, headers, json_encoder)
  File "/Users/rogermukai/Dev/Templates/jwt-example/.venv/lib/python3.10/site-packages/jwt/api_jws.py", line 153, in encode
    key = alg_obj.prepare_key(key)
  File "/Users/rogermukai/Dev/Templates/jwt-example/.venv/lib/python3.10/site-packages/jwt/algorithms.py", line 601, in prepare_key
    raise InvalidKeyError(
jwt.exceptions.InvalidKeyError: Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for EdDSA algorithms

I am expecting to be able to use the EdDSA algorithm as the documentation states that it is possible but it gives no examples.

1

There are 1 best solutions below

2
On

Here is how I figured it out. I ran the below steps in order from top to bottom.

In the terminal/sehlll:

$ openssl genpkey -algorithm Ed25519 -out ed25519key.pem

$ cat ed25519key.pem
-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIKRLPECftB6nJ/ZMQ/OXI1sdwDYUDP7gAq5sea0opeUT
-----END PRIVATE KEY-----

$ openssl pkey -in ed25519key.pem -pubout  
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEA7Adh+4SttVNkOk1C/9XJj6uqtbgFZChpLuz+bq0cSF4=
-----END PUBLIC KEY-----

In python

import jwt

key = """-----BEGIN PRIVATE KEY-----
... MC4CAQAwBQYDK2VwBCIEIKRLPECftB6nJ/ZMQ/OXI1sdwDYUDP7gAq5sea0opeUT
... -----END PRIVATE KEY-----"""

encoded = jwt.encode({"Some":"Key"}, key, algorithm='EdDSA')

print(encoded)
>>> eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJTb21lIjoiS2V5In0.HDsL-x5WdP2rqpL0rq_Ir2dj9c8IEl_qqcfpUEZjncqP8df8Nrz-FGEfnI2-eB7JOGGI2WzZHM_O8vu7ieokCg

public_key = """-----BEGIN PUBLIC KEY-----
... MCowBQYDK2VwAyEA7Adh+4SttVNkOk1C/9XJj6uqtbgFZChpLuz+bq0cSF4=
... -----END PUBLIC KEY-----"""

decoded = jwt.decode(encoded, public_key, algorithms='EdDSA', verify=True)
print(decoded)
>>> {'Some': 'Key'}