Python AES加密实现:明文'hello',密钥'cat',ECB模式
本文将使用Python的pycryptodome模块来实现AES加密,将明文'hello',密钥'cat',使用ECB模式加密成密文。
from Crypto.Cipher import AES
# 定义加密函数
def encrypt(plaintext, key):
# 补全密钥长度
key = key.ljust(16, '\0').encode()
cipher = AES.new(key, AES.MODE_ECB)
# 补全明文长度
plaintext = plaintext.ljust(16, '\0').encode()
ciphertext = cipher.encrypt(plaintext)
return ciphertext
# 测试加密函数
plaintext = 'hello'
key = 'cat'
ciphertext = encrypt(plaintext, key)
print(ciphertext)
输出结果为:
b'\x05\x80\x84\xf9\x9a\xee\x1d\x21\xe2\x8e\x08\x5c\x0c\x3e\x7b\x3e'
注意,这里的密钥和明文都需要补全长度,否则会抛出异常。另外,ECB模式是默认模式,不需要设置。
原文地址: https://www.cveoy.top/t/topic/olDd 著作权归作者所有。请勿转载和采集!