我正在尝试使用以下代码在 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)
Run Code Online (Sandbox Code Playgroud)
但我收到“ValueError:数据必须与 ECB 模式下的块边界对齐”。如果 string 是 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))
Run Code Online (Sandbox Code Playgroud)