我试图在Python 3中使用加密设置套接字聊天,但是在解码UTF-8时会出现错误。
以下是代码:
客户端:
from Crypto.Cipher import AES
from Crypto import Random
import socket, sys
host = 'localhost'
port = 5558
IV = Random.new().read(16)
c = AES.new('abcd1234efgh5678', AES.MODE_CFB, IV)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
data = 'hey'.encode('utf-8') # 1
data = c.encrypt(data) # 2
s.sendall(data)服务器:
from Crypto.Cipher import AES
from Crypto import Random
import socket, sys
host = ''
port = 5558
IV = Random.new().read(16)
c = AES.new('abcd1234efgh5678', AES.MODE_CFB, IV)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(10)
sock, addr = s.accept()
data = sock.recv(512)
data = c.decrypt(data) # 1
data = data.decode('utf-8') # 2
print(data)在运行这些程序之后,服务器会给出以下错误:
UnicodeDecodeError:'utf-8‘编解码器无法解码0位置的字节0xa5 :无效的开始字节
因此,我尝试将服务器代码中的“utf-8”更改为“拉丁语-1”,但每次运行该程序时,它都会打印不同的unicode字符。然后,我交换了客户机和服务器中标记有注释的2行代码,当然,这会导致以下错误:
AttributeError:‘字节’对象没有属性'encode‘
我试过Google,但是所有使用PyCrypto的程序都使用Python2,而不是3。Encrypt & Decrypt using PyCrypto AES 256
http://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/
发布于 2015-08-01 14:24:32
除了上面的代码使用//作为注释(应该是#)之外,我还运行了下面的代码(删除了所有套接字)并发现了错误:在解密之前重新初始化IV。这样你就不会得到原来的值-只是一些胡言乱语,可能无法在utf-8中解码。
您必须将IV发送到服务器(How to communicate AES initialization Vector to client for hybrid cryptosystem)。
from Crypto.Cipher import AES
from Crypto import Random
# CLIENT -----------------------------------------
IV = Random.new().read(16)
c = AES.new('abcd1234efgh5678', AES.MODE_CFB, IV)
data = 'hey'.encode('utf-8') # 1
data = c.encrypt(data) # 2
# SERVER -----------------------------------------
# THIS IS WHERE YOUR CODE GOES WRONG!
# IV = Random.new().read(16)
c = AES.new('abcd1234efgh5678', AES.MODE_CFB, IV)
data = c.decrypt(data) # 1
data = data.decode('utf-8') # 2
print(data)https://stackoverflow.com/questions/31756166
复制相似问题