我们常常遇到这样的需求,需要对一些数据进行加密,以防被别人轻易获取。接下来记录怎么对接口进行加密。常用的加密算法有很多种,接下来将记录一下用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
content = content +
'\0' *
add
elif count >
16 and count %
16 !=
0:
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的整数倍,不足可与服务器端协商补全