Python - 如何通过套接字发送 rsa.key.PublicKey 对象?

Python - How can I send a rsa.key.PublicKey object through socket?

我正在使用 python rsa 模块生成 public/private 密钥对。我想通过套接字连接将 public 密钥发送到另一台计算机。

当我尝试对 public 密钥进行编码以发送它时,出现此错误:

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

除了导致错误的方法之外,我想不出对密钥进行编码的方法。如果我尝试将其转换为字符串、对其进行编码并通过它发送,我将无法使用该密钥来加密任何消息,也没有任何记录的方法可以将其转换回 PublicKey 对象。

这是导致错误的原因:

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

这是pypi上的包和文档:

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

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

使用save_pkcs1和load_pkcs1:

a = pubkey.save_pkcs1(format='DER')
b = rsa.key.PublicKey.load_pkcs1(a, format='DER')