谷歌序列化語法文檔 https://colobu.com/2017/03/16/Protobuf3-language-guide/
現在某些app數據加密不僅僅使用常規的加密算法,還會使用一些協議對數據序列化後進行傳輸,最近就遇到一個採用Google 的 Protobuf 對登錄等請求的參數和響應進行了序列化傳輸,頗費了一番功夫。
一、python安裝和實現Protobuf的example
windows系統下載兩個文件protobuf-python-3.5.1.zip和protoc-3.5.1-win32.zip解壓後在protobuf-python-3.5.1\protobuf-3.5.1\python目錄下運行下面命令進行編譯
python setup.py
build python setup.py
install python setup.py test
將protoc.exe放在protobuf-python-3.5.1\protobuf-3.5.1\src下,同時配置環境變量,終端可以使用。前者包含協議序列化數據的一些文件,後者用來用來編譯proto文件。通過一個example,我們看看如何使用。
1、使用 protobuf 首先需要定義一個 examplepb.proto文件,內容如下
syntax = "proto3";
message Student{
string name = 1;
int32 id = 2;
string sex = 3;
message Performance{
string sbuject = 4;
string score = 5;
}
repeated Performance performance = 4;
}
message School{
string name = 6;
}
message Examplepb{
string age = 1;
repeated Student student = 2;
repeated School school = 3;
}
2、examplepb.proto同級目錄下運行命令 protoc examplepb.proto --python_out=./ 會生成 examplepb_pb2.py文件
3、新建xulihua.py編寫序列化代碼,fanxuliehua.py 反序列化代碼
# -*- coding: utf-8 -*-
from example_protobuf import examplepb_pb2
data_pb = examplepb_pb2.Examplepb()
student = data_pb.student.add()
school = data_pb.school.add()
data_pb.age = "18"
student.name = "張xxxxxx"
student.id = 10080
student.sex = 'men'
pfm = student.performance.add()
pfm.sbuject = "math"
pfm.score = "98"
school.name = "xxxxx university"
print(data_pb.SerializeToString())
with open("example.bin", 'wb') as f:
f.write(data_pb.SerializeToString())
# -*- coding: utf-8 -*-
from example_protobuf import examplepb_pb2
data_pb = examplepb_pb2.Examplepb()
student = data_pb.student.add()
school = data_pb.school.add()
def ListExample(data_pb):
print(data_pb.age)
for person in data_pb.student:
print(person.name)
print(person.id)
print(person.sex)
for pf in person.performance:
print(pf.sbuject)
print(pf.score)
for sh in data_pb.school:
print(sh.name)
with open("example.bin", 'rb') as f:
data_pb.ParseFromString(f.read())
ListExample(data_pb)
上面這些一個完整的谷歌序列化和反序列化數據的過程,操作完就知道逆向app的谷歌序列化協議關鍵就是proto文件的編寫。未完待續