AES 加密算法,AES 为 CBC 模式。
key: 16 个字符的密钥
iv: 16 个字符长的 IV
code = { #加密文本必须为16的倍数
"key1": 'value1',
"key2": 'value1',
"key3": 'value1',
"key4": 'value1',
}
key: 'CwcnldOjID07WHKV'
iv: '1973874772082924'
将code组成json串,加密出的二进制数据采用base64加密。
import base64
from Crypto.Cipher import AES
BS = 16
def padding(s):
return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
def unpadding(s):
return s[0:-ord(s[-1])]
#加密
code = 'hello, world'
key = 'CwcnldOjID07WHKV'
iv = '1973874772082924'
obj = AES.new(key, AES.MODE_CBC, iv)
b = obj.encrypt(padding(code))
aes_code = base64.b64encode(b).decode('utf8')
print('加密数据:', aes_code)
#解密
code2 = 'RmBQezvawfhcWWUWW1K7eg=='
obj = AES.new(key, AES.MODE_CBC, iv)
encrypted = obj.decrypt(base64.b64decode(code2))
decryption_code = unpadding(encrypted.decode('utf8'))
print('解密数据:', decryption_code)
运行结果:
加密数据: RmBQezvawfhcWWUWW1K7eg==
解密数据: hello, world