AES加密时出现字节问题

时间:2020-05-16 18:16:23

标签: python encryption byte aes

我使用Crypto.cipher编写了一个代码,该代码将遍历目录/子目录中的所有文件,并使用AES-ECB对其进行加密。 现在的问题是由于某种原因我得到了这个错误:

提高ValueError(“在ECB模式下加密时出错%d”%结果) ValueError:在ECB模式下加密时出现错误3

我尝试将字节转换为base64,但仍然遇到相同的问题,我最初认为可能只是某些文件以不同的方式编码,但随后我查看了列表和一些文件给出此异常的是.txt,并且其中只有一些数字,因此我不确定是什么问题。

with open(loc, 'rb') as file:
     data = file.read()
     Edata = Encrypt(data)

这是我加密的方式:

def Encrypt(msg): #AES
    pad = lambda x: x + (SIZE - len(x) % SIZE) * PADDING
    print(type(msg))
    msg = pad(msg)
    cipher = AES.new(hkey,AES.MODE_ECB)
    cipherTxt = cipher.encrypt(msg)
    return cipherTxt

编辑: python 3.6

def Decrypt(msg): #AES
    decipher = AES.new(hkey,AES.MODE_ECB)
    plain = decipher.decrypt(msg)
    index = plain.find(b".")
    original = msg[:index]
    return original

1 个答案:

答案 0 :(得分:1)

使用我的加密软件包(来自anaconda)对二进制数据进行加密。您可能使用的是其他程序包-如果您尝试加密字符串,则我的操作会出错。这可能只是个稻草人,但这对我有用:

from Crypto.Cipher import AES
from Crypto.Hash import SHA256
import random

password = "temp"
hashObj = SHA256.new(password.encode("utf-8"))
hkey = hashObj.digest()

def Encrypt(msg, blocksize=16):
    """encrypt msg with padding to blocksize. Padding rule is to fill with
    NUL up to the final character which is the padding size as an 8-bit
    integer (retrieved as `msg[-1]`)
    """
    assert blocksize > 2 and blocksize < 256
    last = len(msg) % blocksize
    pad = blocksize - last
    random_pad = bytes(random.sample(range(255), pad-1))
    msg = msg + random_pad + bytes([pad])
    cipher = AES.new(hkey,AES.MODE_ECB)
    cipherTxt = cipher.encrypt(msg)
    return cipherTxt

def Decrypt(msg): #AES
    decipher = AES.new(hkey,AES.MODE_ECB)
    print('msg size', len(msg))
    plain = decipher.decrypt(msg)
    print('plain', plain)
    original = plain[:-plain[-1]]
    return original


# test binary data
sample = bytes(range(41))
print('sample', sample)
encrypted = Encrypt(sample, 16)
print('encrypted', encrypted)
print(len(sample), len(encrypted))
decrypted = Decrypt(encrypted)
print('decrypted', decrypted)
print('matched', decrypted == sample)

# test blocksize boundary
sample = bytes(range(48))
decrypted = Decrypt(Encrypt(sample))
print('on blocksize', sample==decrypted)