gpt4 book ai didi

python - 无法解码加密的rsa消息python3

转载 作者:行者123 更新时间:2023-12-04 08:26:36 25 4
gpt4 key购买 nike

我正在使用 rsa.encrypt 对消息进行编码,但是我无法使用 .decode() 将加密数据转换为 str .这有点奇怪,因为加密数据是字节字符串,将其转换为 str 应该没有任何问题。

data = [self.id, data, self.my_pubkey] # 实际上不关心组件的类型,它们是正确的

我的代码:

import json
import rsa

def msg(query_type, data):
if query_type == 'PubKey':
try:
query = {"Type": "PubKey",
"Message": {"PubKey": data[0],
"Id": data[1]
}
}
to_send = json.dumps(query)
to_send = to_send.encode()
return to_send
except Exception as ex:
print("Error in creating message")
print(ex)
elif query_type == 'Message':
try:
encrypted_data = rsa.encrypt(data[1].encode('utf-8'), data[2])
print(encrypted_data.decode('utf-8'))
query = {"Type": "Message",
"Message": {"Id": data[0],
"Data": str(encrypted_data)[2:-1]
}
}
pub = rsa.lo
to_send = json.dumps(query)
to_send = to_send.encode()
return to_send
except Exception as ex:
print("Error in creating message")
print(ex)
except Exception as ex:
to_send = str(ex).encode()
return to_send

但是,我收到了这个错误:

Error in creating message
'utf-8' codec can't decode byte 0xfc in position 5: invalid start byte
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\vladi\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\vladi\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\vladi\Documents\Programming\python\Server_Client\Client\client.py", line 28, in send
self.sock.send(str(len(data_to_send)).encode())
TypeError: object of type 'NoneType' has no len()```

最佳答案

只有当您知道字节表示有效的 utf-8 数据时,将字节字符串解码为 utf-8 才有意义。 utf-8 不会解码任意字节字符串:有一种特定格式(当字节 >= 0x80 时,它们被解释为“开始”或“延续”字节,并且必须遵循特定模式;请参阅 the Wikipedia page 了解更多信息)。

另一方面,加密数据(使用几乎所有加密算法)将生成看似随机的字节字符串,几乎肯定不是有效的 utf-8。

解决方案是将加密过程的输出视为字节字符串 - 不要尝试将其解码为字符串,因为它作为字符串没有意义。 Python 恰好为这种情况提供了 bytes/str 区分:bytes 用于二进制数据(例如加密数据),strings 用于文本数据。

为了将二进制数据(作为字节字符串)转储到 JSON,我建议使用像 Base64 这样的编码将字节编码为 ASCII,而不是尝试使用字符串。这将更加高效且更易于调试。

关于python - 无法解码加密的rsa消息python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65230554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com