Skip to main content
 首页 » 编程设计

python之值错误 : Data must be aligned to block boundary in ECB mode

2024年12月31日9zlslch

我正在尝试使用以下代码在 ECB 模式下进行 aes 128 加密。

from Crypto.Cipher import AES 
key = 'abcdefghijklmnop' 
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB) 
msg = cipher.encrypt(b'hello') 
print(msg.hex()) 
decipher = AES.new(key.encode('utf8'), AES.MODE_ECB) 
msg_dec = decipher.decrypt(msg) 
print(msg_dec) 

但我收到“ValueError:在 ECB 模式下数据必须与 block 边界对齐”。如果字符串是 16 的倍数,它工作正常。我不知道如何填充,取消填充。我们如何解决这个问题?请帮忙

请您参考如下方法:

对于padding 和un-padding,您可以使用Crypto 库的内置函数,以下是您问题的有效解决方案。

from Crypto.Util.Padding import pad, unpad 
from Crypto.Cipher import AES 
BLOCK_SIZE = 32 # Bytes 
 
key = 'abcdefghijklmnop' 
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB) 
msg = cipher.encrypt(pad(b'hello', BLOCK_SIZE)) 
print(msg.hex()) 
decipher = AES.new(key.encode('utf8'), AES.MODE_ECB) 
msg_dec = decipher.decrypt(msg) 
print(unpad(msg_dec, BLOCK_SIZE))