AES,高级加密标准(Advanced Encryption Standard)。是用来替代 DES,目前比较流行的对称加密算法。对称加密算法也就是加密和解密用相同的密钥。
AES 只是个基本算法,实现 AES 有几种模式,主要有 ECB、CBC、CFB 和 OFB 这几种。
以下介绍AES的ECB模式加解密方案,该方案实现超出16个字符加密密文处理,即不足16位补足16位。
import json from Crypto.Cipher import AES import base64 import requests import urllib.parse #加密 def aes_encrypt(key, data): BLOCK_SIZE = 16 # Bytes #补位 pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * \ chr(BLOCK_SIZE - len(s) % BLOCK_SIZE) key = key.encode('utf8') data = pad(data) cipher = AES.new(key, AES.MODE_ECB) result = cipher.encrypt(data.encode()) encodestrs = base64.b64encode(result) enctext = encodestrs.decode('utf8') return enctext #解密 def aes_decrypt(key, data): BLOCK_SIZE = 16 # Bytes #去补位 unpad = lambda s: s[:-ord(s[len(s) - 1:])] key = key.encode('utf8') data = base64.b64decode(data) cipher = AES.new(key, AES.MODE_ECB) text_decrypted = unpad(cipher.decrypt(data)) text_decrypted = text_decrypted.decode('utf8') return text_decrypted #测试 if __name__ == '__main__': key = 'test' data = 'asdfasdfasdfasdfasdfasdfasdfsdaf' ecdata = aes_encrypt(key, data) aes_decrypt(key, ecdata)
转载请注明:永盟博客 » Python通过AES实现对称加密