Ad

Python - How Can I Send A Rsa.key.PublicKey Object Through Socket?

- 1 answer

I'm using the python rsa module to generate a public/private key pair. I want to send the public key to the other computer through a socket connection.

When I try to encode the public key to send it, I get this error:

  File "chatclient.py", line 128, in <module>
    s.sendall(pubkey.encode('utf-8'))
AttributeError: 'PublicKey' object has no attribute 'encode'

I cannot figure out a way to encode the key other than the method that causes the error. If I try to convert it to a string, encode it and send it through, I cannot use the key to encrypt any messages, nor are there any documented ways to turn it back into a PublicKey object.

This is what causes the error:

s.sendall(pubkey.encode('utf-8'))

Here's the package on pypi and the documentation:

https://pypi.org/project/rsa/

https://stuvel.eu/python-rsa-doc/usage.html

Ad

Answer

Use save_pkcs1 and load_pkcs1:

a = pubkey.save_pkcs1(format='DER')
b = rsa.key.PublicKey.load_pkcs1(a, format='DER')
Ad
source: stackoverflow.com
Ad