我正在使用以下代码在 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 模式下的块边界对齐”。如果字符串是 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))
使用 pycryptodomex 改进@Abhishake Gupta 的回答
pip install pycryptodomex
import base64
from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad, unpad
###################
class Cryptor:
def __init__(self, key):
self.SECRET_KEY = str(key).encode("utf-8")
self.BLOCK_SIZE = 32 # Bytes
self.CIPHER = AES.new(self.SECRET_KEY, AES.MODE_ECB) # never use ECB in strong systems obviously
def encrypt(self, text):
text = str(text).encode("utf-8")
return base64.b64encode(self.CIPHER.encrypt(pad(text, self.BLOCK_SIZE))).decode("utf-8")
def decrypt(self, encoded_text):
self.CIPHER = AES.new(self.SECRET_KEY, AES.MODE_ECB)
return unpad(self.CIPHER.decrypt(base64.b64decode(encoded_text)), self.BLOCK_SIZE).decode("utf-8")
cryptor = Cryptor("1234567890123456")
text = "hello world"
text = cryptor.encrypt(text)
print(text)
print(cryptor.decrypt(text))