如何在二进制文件中忽略\ n,直到出现实际的换行标记

时间:2019-04-27 04:06:38

标签: python-3.x sockets utf-8 binary aes

我有一些要编码的文本。编码后,其中将带有“ \ n”。然后,我用python添加b'\ n'来添加新行。我的套接字认为,第一个\ n实际上是文本的一部分,是文件的结尾。

我已经浏览了我的代码,这只是我不知道如何解决的事情。

生成二进制数据

print("Calculating Key")
sharedKey = str((int(recieverPublicKey) ** int(privateKey)) % int(mod))
sharedKey = hashlib.sha256(sharedKey.encode())
sharedKey = sharedKey.hexdigest()
sharedKey = sharedKey[0:32]
print("Encrypting Key")
initVector = 16 * '\x00'
sharedKey = bytes(str(sharedKey), encoding='utf-8')
encryptor = AES.new(sharedKey, AES.MODE_CBC, initVector)
encryptedKey = encryptor.encrypt(dencryptionKey)
print(encryptedKey)
time.sleep(0.1)
print("Sending Encryption Key")
sock.sendall(encryptedKey + b'\n')

解码

sharedKey = str((int(senderPublicKey ** int(privateKey))) % int(mod))
sharedKey = hashlib.sha256(sharedKey.encode())
sharedKey = sharedKey.hexdigest()
sharedKey = sharedKey[0:32]
initVector = 16 * '\x00'
print("Recieving Encryption Key")
time.sleep(0.1)
print("Decrypting Key")
encryptedKey = clientFile.readline()
print(encryptedKey)
encryptedKey = encryptedKey.strip().decode()
print(encryptedKey)
initVector = 16 * '\x00'
sharedKey = bytes(str(sharedKey), encoding='utf-8')
decryptor = AES.new(sharedKey, AES.MODE_CBC, initVector)
encryptedKey = encryptedKey[2:-2]
print(encryptedKey)
for x in range(8):
    encryptedKeyPart = encryptedKey[0:16]
    print(encryptedKey)
    encryptedKey = encryptedKey[16:-1]
    dencryptionKey = dencryptionKey +    decryptor.decrypt(encryptedKeyPart).decode('utf-8')
    print(dencryptionKey)

接收方的输出

b';l\xb8\xd7{\xa7Wt\x99\xb6\xc2\xfa\xf8\x8c\xe6\xd7=\x1d\x8e\x0b\r\x8e\xa4\xee\xa3\x84\xca\xfd\x91L\xda\xbb\x82\xc3\x93\x0f\xec\xd9o\xa7V\x1fs\x89{\x87\xd3\xf0\xc3\xba\x8f\xd9\xd0v\x18k-\xd9\xb1C&Y\x82+\xb8\xb6\x85:\xfd\x9f\x13\xea\xd8v\xadG\x11_\xbf4r\xb6\xa3\n'

发送方的输出

b';l\xb8\xd7{\xa7Wt\x99\xb6\xc2\xfa\xf8\x8c\xe6\xd7=\x1d\x8e\x0b\r\x8e\xa4\xee\xa3\x84\xca\xfd\x91L\xda\xbb\x82\xc3\x93\x0f\xec\xd9o\xa7V\x1fs\x89{\x87\xd3\xf0\xc3\xba\x8f\xd9\xd0v\x18k-\xd9\xb1C&Y\x82+\xb8\xb6\x85:\xfd\x9f\x13\xea\xd8v\xadG\x11_\xbf4r\xb6\xa3\ng\xb0\xde\xa9jW\x8d\x85T\x06mR\x0e\xfe\xcar\xaa\x17\x98j\x92lV\x07\xf2}\xad%\x0c\x01\xe4\xf1\xd7=\x8a\xa7\xeb\xd2\xb2c\xb8\x88\xb0\x9b\n'

我希望它接收所有数据并开始解密文本。程序在\ n处停止,该\ n应该是文本的一部分,而没有读取其余部分,导致.decode('utf-8')由于未完成而引发错误。

1 个答案:

答案 0 :(得分:0)

如果要发送的数据包含换行符,则不能使用换行符作为消息的分隔符。像在other question and my answer中一样,发送加密密钥的大小和换行符,然后发送加密密钥。在接收端,接收换行符终止的加密密钥的大小,然后准确读取该密钥本身的字节数。