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条)

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目