AES CBC PKCS7加密解密算法 Python实现
•技术
92
0
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
# 16位
key = '1a1a1a1a1a1a1a1a'
# 16位
iv = '1234567890000000'
# 解密
# 参数:密文
def decrypt(ciphertext):
b_text = bytes.fromhex(ciphertext)
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
try:
plaintext = cipher.decrypt(b_text).decode('utf-8')
except UnicodeDecodeError as e:
print(e)
print("key不正确")
exit(-1)
else:
return plaintext
# 加密 参数:明文
def encrypt(plaintext: str):
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
pad_pkcs7 = pad(plaintext.encode('utf-8'), AES.block_size, style="pkcs7")
ciphertext = bytes.hex(cipher.encrypt(pad_pkcs7))
return ciphertext
if __name__ == '__main__':
plaintext_str = "this is a test str."
en_str = encrypt(plaintext_str)
de_str = decrypt(en_str)
# 加密后的密文
print(en_str)
# 解密后的明文
print(de_str.encode('utf-8'))