1、概念简介
2、算法介绍
- AES:对称式加密解密
3、代码实现
3.1、AES实现
- python实现
类库安装:pip install pycryptodome
请求加密:
# -*- coding= utf-8 -*-
"""
@DevTool : PyCharm
@Author : gzh
@DateTime : 2024/1/26 14:29
@FileName : encryptDemo.py
"""
from Crypto.Cipher import AES
from Crypto.Util import Padding
import base64
v_key = 'UYIASDF8080ASDF7'.encode()
v_iv = 'SADFJK2346L834DF'.encode()
source_str = "Alex is a monkey!"
source_str_pad = Padding.pad(data_to_pad=source_str.encode(), block_size=16)
print("源字符值字节位补充前:", source_str)
print("源字符值字节位补充后:", source_str_pad)
obj_aes = AES.new(v_key, AES.MODE_CBC, v_iv)
source_str_aes = obj_aes.encrypt(source_str_pad)
print("源字符AES加密后:", source_str_aes)
source_str_base64_encode = base64.b64encode(source_str_aes).decode()
print("源字符base64编码后:", source_str_base64_encode)
source_str_base64_decode = base64.b64decode(source_str_base64_encode)
print("源字符base64解码后:", source_str_base64_decode)
加密步骤:
A:设置 key 和 偏移值 iv;
B:将源码转为二进制编码,同时按照 16字节数倍数补齐;
C:将编码后字符串 AES加密;
D:将加密后字符串进行 base64编码;
响应解密:
# -*- coding= utf-8 -*-
"""
@DevTool : PyCharm
@Author : gzh
@DateTime : 2024/1/26 16:40
@FileName : decryptDemo.py
"""
from Crypto.Cipher import AES
from Crypto.Util import Padding
import base64
v_key = 'UYIASDF8080ASDF7'.encode()
v_iv = 'SADFJK2346L834DF'.encode()
target_str = "AJdn7u00t7e0DAa1rZLU5WAfKbkAIuRofxp3VWmY8nw="
print("响应结果base64解码前:", target_str)
target_str_base64_decode = base64.b64decode(target_str.encode())
print("响应结果base64解码后:", target_str_base64_decode)
obj_aes = AES.new(v_key, AES.MODE_CBC, v_iv)
target_str_aes = obj_aes.decrypt(target_str_base64_decode)
print("响应结果AES解密后:", target_str_aes)
target_str_unpad = Padding.unpad(padded_data=target_str_aes, block_size=16)
print("响应结果字节位补充前:", target_str_unpad.decode())
================================================ over =============================================