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

时间:2019-05-12 20:30:43

标签: python encryption 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))

1 个答案:

答案 0 :(得分:0)

默认情况下,bytes.decrypt()函数需要使用UTF-8编码的字符串。但是,并非每个字节序列都是有效的UTF-8序列。在您的情况下,cipher.decrypt()(可能返回 any 个字节序列)返回一个字节序列,这不是有效的UTF-8序列。因此bytes.decode()函数会引发错误。

cipher.decrypt()返回非UTF-8字符串的实际原因是您的代码中的错误:

您的加密文件格式包含非utf-8数据。其格式如下:

  • 16个字节的len信息(未加密,以UTF-8编码)
  • 16字节IV(未加密的二进制,即非UTF-8编码)
  • n字节有效负载(加密,UTF-8编码)

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

相关问题