dqst96444 2019-09-06 08:46
浏览 120

python中的JSON编码dict和golang中的映射不匹配

I am generating a HMAC, sha256 hash of a json encoded python dict using json. Lets call it hash1. This is my signature which am sending with JWT. Then I would like to verify this signature at another service in Go. I am using the data that i have in a map(same as python dict), json encoding and hashing it(hash2) However, hash1 and hash2 are different. I learned that this is due to python json adding space between elements in dict. Golang json library doesn't add any space. Is there a way I can work around this?

some_data = {'a':1, 'b':2}
json_str1 = json.dumps(some_data, sort_keys=True)
some_data := map[string]int{"a":1, "b":2}
json_str2 = json.Marshal(some_data)

EDIT: As suggested in one of the answers, using separators in json.dumps would solve the problem. Unfortunately, I do not own the python side code, so can't do the changes there.

  • 写回答

2条回答 默认 最新

  • du5910 2019-09-06 08:50
    关注

    Can't say anything about Go, but when i was generating hash in javascript i had the same issue. You need to play around a bit with separators, maybe something like json.dumps(data, separators=(',', ':')).encode('utf-8') will work.

    评论

报告相同问题?