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

Cat*_*tYT 2 python sockets rsa

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

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

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

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

这就是导致错误的原因:

s.sendall(pubkey.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

这是 pypi 上的包和文档:

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

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

Cat*_*tYT 5

使用 save_pkcs1 和 load_pkcs1:

a = pubkey.save_pkcs1(format='DER')
b = rsa.key.PublicKey.load_pkcs1(a, format='DER')
Run Code Online (Sandbox Code Playgroud)