我用编码的消息rsa.encrypt
,但当时我无法加密的数据转换为一个str
带.decode()
。有点奇怪,因为加密的数据是字节字符串,将其转换为不会有任何问题str
。
data = [self.id, data, self.my_pubkey] # actually don't care about type of components, they are correct
我的代码:
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时,它们被解释为“开始”或“继续”字节,并且必须遵循某些模式;有关更多信息,请参见Wikipedia页面)。
另一方面,加密数据(使用几乎所有加密算法)将生成看起来随机的字节字符串,几乎可以肯定该字符串不是有效的utf-8。
解决方案是将加密过程的输出视为字节字符串-不要尝试将其解码为字符串,因为它将作为字符串没有意义。Python正是针对这种情况提供了byte / str的区分:字节用于二进制数据(例如,加密数据),字符串用于文本数据。
要将二进制数据(作为字节字符串)转储到JSON中,我建议使用Base64之类的编码将字节编码为ASCII,而不是尝试使用字符串。这将更加高效并且更容易调试。