python对称加密AES的使用
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/53540ee261a7b60dded7a05b69539d41.png)
aes安装
pip install pycryptodome
加密库引用
from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
import base64
完整代码
from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
import base64
def AES_encrypt(data, key):
key = pad(key.encode(), block_size=16)
aes = AES.new(key, AES.MODE_ECB)
pad_data = pad(data.encode(encoding='utf-8'), block_size=16, style='pkcs7')
encrypt_data = aes.encrypt(pad_data)
encrypt_str = base64.encodebytes(encrypt_data).decode(encoding='utf-8')
return encrypt_str
def AES_decrypt(encrypt_data, key):
key = pad(key.encode(), block_size=16)
aes = AES.new(key, AES.MODE_ECB)
b64_data = base64.decodebytes(encrypt_data.encode(encoding='utf-8'))
decrypt = aes.decrypt(b64_data)
decrypt_str = unpad(decrypt, block_size=16, style='pkcs7').decode(encoding='utf-8')
return decrypt_str
if __name__ == '__main__':
passwd = '1234567890'
src_data = 'python对称加密AES的使用'
encrypt_res = AES_encrypt(src_data, passwd)
print(encrypt_res)
src_data = AES_decrypt(encrypt_res, passwd)
print(src_data)
pass
测试结果
R1gH/LPQwUGZ+fZZcmAcsWuKfKRhgrVU0qhsB0tyLw0=
python对称加密AES的使用
参考
AEA加密解密知识参考