我们在采集数据时,经常会碰到被protobuf序列化的数据,无法直接读出来,正常情况下需要有.proto文件生成所对应语言的解析包。

一、Python protobuf解析库-blackboxprotobuf
blackboxprotobuf是一个Python库,可在黑盒的情况下直接把protobuf数据解析为JSON数据。
安装依赖:pip3 install blackboxprotobuf
序列化:
message_type = {'1': {'type': 'int', 'id': ''}, '2': {'type': 'string', 'name': ''}}
value = {'1': 123, '2': 'Hello Word'}
data = blackboxprotobuf.encode_message(value, message_type)
print(data)
反序列化:
temp_message, typedef = blackboxprotobuf.protobuf_to_json(data)
print(temp_message)
print(typedef)

二、逆向解析Protobuf数据
准备工作:
首先需要在电脑上安装Protobuf相关环境,这一步我这里就略了,可以自己查下网上资料。
逆向步骤:
- 首先需要把序列化的Protobuf数据保存为文件;
- 在终端中使用命令 protoc –decode_raw < data.txt 查看反序列结果

- 根据反编译结果,编写.proto文件
syntax="proto3";
message TestMessage {
int32 id = 1;
string name = 2;
}
- 终端执行 protoc –python_out=. test.proto 命令生成Python包

- 编写Python代码反序列化数据
import test_pb2
with open('data.txt', 'rb') as f:
data = test_pb2.TestMessage()
data.ParseFromString(f.read())
print(data.id)
print(data.name)
正文完