我正在编写一个应用程序,用于计算和验证 protobuf 结构的签名。它的计算方式类似于 sign(protobuf_message.SerializeAsString())
。
我能否确定,相同的 protobuf_message
将被相同地序列化(使用不同版本的库(但仅使用 proto2 编码),在不同的计算机上,在不同的条件下),反之亦然?
最佳答案
Protobuf documentation精确定义了二进制消息格式。
它特别指出:
While you can use field numbers in any order in a .proto, when a message is serialized its known fields should be written sequentially by field number, as in the provided C++, Java, and Python serialization code. This allows parsing code to use optimizations that rely on field numbers being in sequence. However, protocol buffer parsers must be able to parse fields in any order, as not all messages are created by simply serializing an object – for instance, it's sometimes useful to merge two messages by simply concatenating them.
因此,只要您不通过连接其他消息来生成新消息,并使用 protobuf 库本身提供的序列化代码,序列化的消息应该是相同的。如果您使用某些第三方 protobuf 绑定(bind)(例如 C#),您应该检查它是否符合上面的建议。
关于c++ - protobuf 序列化/解析操作是双射的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29606763/