Deserializing public key with python's cryptography module
Asked Answered
S

2

8

I am writing a python script that involves sending a public key over a network. I am using <https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/.>

public_key = self.node.public_key
pem = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)

deserialized_key = load_pem_public_key(pem)

I get the error:

TypeError: load_pem_public_key() missing 1 required positional argument: 'backend'

I am therefore unable to deserialize the key - I am confused because according to the documentation, load_pem_public_key() takes 1 required argument (data) and 1 optional argument (backend).

Schistosome answered 4/9, 2020 at 9:8 Comment(2)
You should be sending the entire certificate, not just the public key.Sclerosed
cryptography < 3.1 requires backend arguments. You can get a default backend with from cryptography.hazmat.backends import default_backend and pass default_backend() (note that you must invoke it as a method!) as the argument. You can also upgrade to 3.1+.Egesta
C
12

Looks like you use cryptography==3.0 or lower where backend argument is required https://github.com/pyca/cryptography/blob/3.0/src/cryptography/hazmat/primitives/serialization/base.py#L19

Bump to cryptography==3.1 or put something to backend arg

Chantal answered 4/9, 2020 at 9:28 Comment(0)
G
0

Even with cryptography==3.1 I still had the problem.

I can't provide the backend arg either because it was triggered in a library (python-jose==3.1). Upgrading to python-jose==3.2 (=current latest) didn't help either.

Installing python-jose-cryptodome==1.3.2 did help.


Relevant section of the python-jose documentation:

Th[e naive python] backend is always installed but any other backend will take precedence if one is installed.

Gyrostat answered 12/1, 2021 at 18:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.