常用-加密算法

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 =============================================

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值