我们常常遇到这样的需求,需要对一些数据进行加密,以防被别人轻易获取。接下来记录怎么对接口进行加密。常用的加密算法有很多种,接下来将记录一下用AES加密算法对项目接口进行加密:
安装PyCrypto库
pip3 install pycrypto
服务端
from Crypto.Cipher import AES
import base64
from django.http import JsonResponse
def getInfo(request):
data = request.POST.get("data","")
key = "the requests key"
vi = b"1234567890123456"
decryptor = AES.new(key,AES.MODE_CBC,vi)
# 解密并解码
info = decryptor.decrypt(base64.urlsafe_b64decode(data)).decode()
# 去掉右边空格
info = info.rstrip("\0")
import json
# 将字符串转成字典对象
d = json.loads(info)
return JsonResponse({"code":"ok"})
客户端
from Crypto.Cipher import AES
import base64,requests
class Message(object):
def __init__(self,key,vi):
self.key = key
self.vi = vi
def encryText(self,content)
length = 16
count = len(content)
if count < length:
add = length - count
# 加密字符小于16位时,后面补空格
content = content + '\0' * add
elif count > 16 and count % 16 != 0: # 位数大于16并且不是16的倍数时
add = length - (count % length)
# 后面补空格
content = content + '\0' * add
encryptor = AES.new(self.key,AES.MODE_CBC,self.vi)
# 加密
content = encryptor.encrypt(content)
return base64.urlsafe_b64encode(content)
if __name__ == "__main__"
import json
data = {"name":"python"}
encryptData = Message("the requests key",b"1234567890123456").encryText(json.dumps(data))
r = requests.post("http://127.0.0.1:8000/search_all/",data={"data":encryptData})
print(r.json())
注意
- 客户端与服务端key与vi一定要保持一致
- key的长度必须为16、24或32位
- vi长度必须为16位,否则将直接报错
- 加密的内容必须为16的整数倍,不足可与服务器端协商补全