我在文件中有一条加密的消息,并通过以下代码进行了加密。 我编写了一个函数来解密此消息。我知道用于加密的密码。
但是我遇到了以下错误:
python3 decrypt.py enim_msg.txt
Traceback (most recent call last):
File "decrypt.py", line 45, in <module>
print(":: Decrypted: \n" + bytes.decode(decrypted))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 2: invalid start byte
请问如何解决此问题? 我的解密功能不正确吗?
import os
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
def encrypt(key, filename):
chunksize = 64*1024
outputFile = "en" + filename
filesize = str(os.path.getsize(filename)).zfill(16)
IV = Random.new().read(16)
encryptor = AES.new(key, AES.MODE_CBC, IV)
with open(filename, 'rb') as infile:
with open(outputFile, 'wb') as outfile:
outfile.write(filesize.encode('utf-8'))
outfile.write(IV)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b' ' * (16 - (len(chunk) % 16))
outfile.write(encryptor.encrypt(chunk))
def getKey(password):
hasher = SHA256.new(password.encode('utf-8'))
return hasher.digest()
def decrypt(enc, password):
#print(":: enc => " + enc)
private_key = hashlib.sha256(password.encode("utf-8")).digest()
iv = enc[:16]
cipher = AES.new(private_key, AES.MODE_CBC, iv)
return cipher.decrypt(enc[16:])
password = "azerty123"
secret_file_path = sys.argv[1]
the_file = open(secret_file_path, "rb")
encrypted = the_file.read()
decrypted = decrypt(encrypted, password)
the_file.close()
print(":: Decrypted: \n" + bytes.decode(decrypted))
答案 0 :(得分:0)
默认情况下,bytes.decrypt()函数需要使用UTF-8编码的字符串。但是,并非每个字节序列都是有效的UTF-8序列。在您的情况下,cipher.decrypt()
(可能返回 any 个字节序列)返回一个字节序列,这不是有效的UTF-8序列。因此bytes.decode()
函数会引发错误。
cipher.decrypt()
返回非UTF-8字符串的实际原因是您的代码中的错误:
您的加密文件格式包含非utf-8数据。其格式如下:
您必须确保解密时仅解码文件的UTF-8编码部分。此外,您必须确保仅解密文件的加密部分(如评论中所述)