Glen E. Renner
Glen E. Renner

Reputation: 117

How to restore a EC public key from public bytes or public numbers in python (cryptography module)

I'm trying to send a public key to a remote peer in order to calculate a shared key. I'm using python's cryptography module, and I'm using ec not rsa.

I can send over the public numbers:

value = ecdh_public_key.public_numbers()

or the public bytes:

value = ecdh_public_key.public_bytes()

but in both cases I don't know how to convert them back into an ec public key object in the other side.

The whole code:

# Generating ECDH private/public key
ecdh_private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
ecdh_public_key = ecdh_private_key.public_key()

# exchange public keys
value = ecdh_public_key.public_numbers()

EDIT: The value I get after using public_bytes() is PKCS1 key. So if there's a way I can convert a PKCS1 key to a public key object it will work.

Upvotes: 0

Views: 1283

Answers (1)

Glen E. Renner
Glen E. Renner

Reputation: 117

I figured it out. By importing load_pem_public_key method like this:

from cryptography.hazmat.primitives.serialization import load_pem_public_key

then use it to create a public key object from public bytes:

public_key = load_pem_public_key(remote_public_bytes, default_backend())

Upvotes: 1

Related Questions