使用 AES 加密时的字节问题

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


raise ValueError("Error %d while encrypting in ECB mode" % result) ValueError: Error 3 while encrypting in ECB mode


我尝试将字节转换为 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


叮当猫咪
浏览 139回答 1
1回答

扬帆大鱼

加密二进制数据适用于我的加密包(来自 anaconda)。您可能正在使用不同的包 - 如果您尝试加密字符串,我的包会出错。这可能只是一个稻草人,但这对我有用:from Crypto.Cipher import AESfrom Crypto.Hash import SHA256import randompassword = "temp"hashObj = SHA256.new(password.encode("utf-8"))hkey = hashObj.digest()def Encrypt(msg, blocksize=16):&nbsp; &nbsp; """encrypt msg with padding to blocksize. Padding rule is to fill with&nbsp; &nbsp; NUL up to the final character which is the padding size as an 8-bit&nbsp; &nbsp; integer (retrieved as `msg[-1]`)&nbsp; &nbsp; """&nbsp; &nbsp; assert blocksize > 2 and blocksize < 256&nbsp; &nbsp; last = len(msg) % blocksize&nbsp; &nbsp; pad = blocksize - last&nbsp; &nbsp; random_pad = bytes(random.sample(range(255), pad-1))&nbsp; &nbsp; msg = msg + random_pad + bytes([pad])&nbsp; &nbsp; cipher = AES.new(hkey,AES.MODE_ECB)&nbsp; &nbsp; cipherTxt = cipher.encrypt(msg)&nbsp; &nbsp; return cipherTxtdef Decrypt(msg): #AES&nbsp; &nbsp; decipher = AES.new(hkey,AES.MODE_ECB)&nbsp; &nbsp; print('msg size', len(msg))&nbsp; &nbsp; plain = decipher.decrypt(msg)&nbsp; &nbsp; print('plain', plain)&nbsp; &nbsp; original = plain[:-plain[-1]]&nbsp; &nbsp; return original# test binary datasample = 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 boundarysample = bytes(range(48))decrypted = Decrypt(Encrypt(sample))print('on blocksize', sample==decrypted)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python