# 使用 AES 加密时的字节问题

2022-11-24 14:54:32

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

with open(loc, 'rb') as file:

Edata = Encrypt(data)

def Encrypt(msg): #AES

pad = lambda x: x + (SIZE - len(x) % SIZE) * PADDING

print(type(msg))

cipher = AES.new(hkey,AES.MODE_ECB)

cipherTxt = cipher.encrypt(msg)

return cipherTxt

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 回答

TA贡献1491条经验 获得超9个赞

from Crypto.Cipher import AES

from Crypto.Hash import SHA256

import random

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

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)

• 1 回答
• 0 关注
• 8 浏览

0/150