dpsr1670 2015-07-12 18:50
浏览 94
已采纳

是否可以确保mgo bson编组保留结构组件的顺序?

I am saving go structs in mongo using mgo. I wish to save them with a hash of that struct (and a secret) to determine whether they have been tampered with (and I do not wish the mongo db itself to have the secret).

Currently I am hashing the structs by serializing them using gob whose ordering of struct components is well-defined. This works great, save when I go to reread the struct from mango, things have changed - to be precise the time values in mongo have truncated accuracy compared to go - therefore the hashes do not match up.

My planned work around for this is simply to marshall and unmarshall the struct from BSON before calculating the hash, i.e.:

  • Marshal struct to BSON
  • Unmarshal struct from BSON (thereby losing precision on time)
  • Marshall struct to gob and hash resultant []byte
  • Put hash in struct
  • Save struct to mongo

Now, that's more than a little circuitous.

If I could guaranteed that the BSON itself always preserved order of components in structs, I could:

  • Marshal struct to BSON
  • hash resultant byte[]
  • Put hash in struct
  • Save struct to mongo

Which would be less nasty (albeit that it would still require converting to BSON twice).

Any ideas?

  • 写回答

2条回答 默认 最新

  • dspows0637 2015-07-16 13:34
    关注

    Answering your actual question, yes, you can trust mgo/bson to always marshal struct fields in the order they are observed in the code. Although not yet documented (issue), this is very much intentional behavior, and even mgo itself depends on it internally.

    Now, responding to your intended usage: don't do that. The fact fields are in a guaranteed order does not mean the binary format is stable as a whole. Even now there are known ways the output can change without breaking even the existing clients, but that would break a hash of its output.

    Here is some suggested reading to understand a bit better the ins and outs of the problem you are trying to solve (I'm the author):

    This is precisely addressing the issue of marshaling an arbitrary or map with arbitrary fields and keys in a stable way, to obtain a stable hash out of it for signatures. The reference implementation is in Go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection