使用 PyCrypto AES 和 sha256 解密加密的秘密

Decrypt a encrypted secret using PyCrypto AES & sha256

我在文件中有一条加密消息,由以下代码加密。 我写了一个函数来解密这条消息。我知道用来加密它的密码。

但是我得到了以下错误:

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))

默认情况下,bytes.decrypt() 函数需要一个 UTF-8 编码的字符串。但并非每个字节序列都是有效的 UTF-8 序列。在您的情况下 cipher.decrypt()(可能 return 任何 字节序列)returned a byte-sequence,这不是有效的 UTF -8 序列。因此 bytes.decode() 函数引发了一个错误。

cipher.decrypt() return 编辑 non-UTF-8 字符串的实际原因是您的代码中存在错误:

您的加密文件格式包含 non-utf-8 数据。它的格式是这样的:

  • 16 字节长度信息(未加密,UTF-8 编码)
  • 16 字节 IV(未加密,二进制即 non-UTF-8 编码)
  • n 字节负载(加密,UTF-8 编码)

您必须确保在解密时只解码文件的 UTF-8 编码部分。此外,您必须确保只解密文件的加密部分(如评论中所述)