无法解码加密的 rsa 消息 python3

Cannot decode encrypted rsa message python3

我正在使用 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 时,它们被解释为“开始”或“继续”字节,并且必须遵循特定模式;请参阅 the Wikipedia page 了解更多信息).

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

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

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

如果有一天有人需要它

import rsa
import base64
---------
pub, priv = rsa.newkeys(512)
---------
message_to_send = "Hello Vlad!"
b_message = message_to_send.encode()
encrypted = rsa.encrypt(b_message, pub)
encrypted_b64 = base64.b64encode(encrypted)
encrypted_b64_string = encrypted_b64.decode()
# -- sending via socket --
message_to_recieve = encrypted_b64_string
encrypted_b64 = message_to_recieve.encode()
encrypted = base64.b64decode(encrypted_b64)
b_final_message = rsa.decrypt(encrypted, priv)
final_message = b_final_message.decode()
-----------------------
print('message_to_send')
print(message_to_send)
print('b_message')
print(b_message)
print('encrypted')
print(encrypted)
print('encrypted_b64')
print(encrypted_b64)
print('encrypted_b64_string')
print(encrypted_b64_string)
print('message_to_recieve')
print(message_to_recieve)
print('encrypted_b64')
print(encrypted_b64)
print('encrypted')
print(encrypted)
print('b_final_message')
print(b_final_message)
print('final_message')
print(final_message)
---------------
message_to_send
Hello Vlad!
b_message
b'Hello Vlad!'
encrypted
b'5\x11\xeds\r\rF)&mt\x8bR\xc7\x9cf\x98/V#b[\x04\xe3\x90\x1f$R?=\xaa\xe0\x02\xba\xbeg\xec^F\xae+\x17\xab\xc1\xd1b[\xed\xce\xd8\x15\x18~99\x8a\xc3\xe0^2\x88Iy\xb5'
encrypted_b64
b'NRHtcw0NRikmbXSLUsecZpgvViNiWwTjkB8kUj89quACur5n7F5GrisXq8HRYlvtztgVGH45OYrD4F4yiEl5tQ=='
encrypted_b64_string
NRHtcw0NRikmbXSLUsecZpgvViNiWwTjkB8kUj89quACur5n7F5GrisXq8HRYlvtztgVGH45OYrD4F4yiEl5tQ==
message_to_recieve
NRHtcw0NRikmbXSLUsecZpgvViNiWwTjkB8kUj89quACur5n7F5GrisXq8HRYlvtztgVGH45OYrD4F4yiEl5tQ==
encrypted_b64
b'NRHtcw0NRikmbXSLUsecZpgvViNiWwTjkB8kUj89quACur5n7F5GrisXq8HRYlvtztgVGH45OYrD4F4yiEl5tQ=='
encrypted
b'5\x11\xeds\r\rF)&mt\x8bR\xc7\x9cf\x98/V#b[\x04\xe3\x90\x1f$R?=\xaa\xe0\x02\xba\xbeg\xec^F\xae+\x17\xab\xc1\xd1b[\xed\xce\xd8\x15\x18~99\x8a\xc3\xe0^2\x88Iy\xb5'
b_final_message
b'Hello Vlad!'
final_message
Hello Vlad!