0x00 Python 需要导入的模块
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
0x01 AES加密代码
def AES_encrypt(secret_key,data):
"""
:param secret_key [str] : 加密秘钥
:param data [str] : 需要加密数据
:return [str] :
"""
BLOCK_SIZE = 16
pad = lambda s: (s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE))
raw = pad(str(data))
cipher = AES.new(secret_key.encode(), AES.MODE_ECB)
encrypted_text = cipher.encrypt(bytes(raw, encoding='utf-8'))
encrypted_text_hex = str(b2a_hex(encrypted_text), encoding='utf-8')
return encrypted_text_hex
0x02 AES解密代码
def AES_decrypt(secret_key,encrypted_text_hex):
"""
:param secret_key [str] : 加密秘钥
:param encrypted_text_hex [str]: # 加密后的 data 字符串
:return [str]:
"""
# 去掉 PKCS5Padding 的填充
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
# 通过 key 值进行
cipher = AES.new(secret_key.encode(), AES.MODE_ECB)
data_response = unpad(cipher.decrypt(a2b_hex(encrypted_text_hex))).decode('utf8')
return data_response
0x03 测试代码
secret_key="z1s4d5e4rt5g4h5y"
dataEncrypt=AES_encrypt(secret_key,"123456789")
print(dataEncrypt)
data=AES_decrypt(secret_key,dataEncrypt)
print(data)
0x04 测试结果
8f0eddc4bd5f22006087afcfa6e18e6e
123456789