0

I'm using the JSON file from https://filesamples.com/samples/code/json/sample1.json With this JSON string as input and string abc123 as secret key, I'm trying to generate a HMAC SHA256 signature using the following python code.

import hmac
import hashlib
import json
secret = 'abc123'

# Contents of sample1.json
message = '''{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
}'''
# message = json.dumps(message)
hash = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest()
print(hash)

I'm expecting beedda97cf89103141f2e44cbc6241ced093537c499887289b34d5a3ebc90e97 but I'm getting 2383734eba9903278b5e91766fef3413f35c823090d01196ab5c682af19f4c81. If I read the JSON file directly, I get a signature different from both. But according to my use case, I can't read the JSON file as such. I have to copy paste the contents in the code itself.

I could get the expected result, with this website https://www.freeformatter.com/hmac-generator.html and this https://tools.chilkat.io/hmac#macResult. I think some formatting/encoding is getting messed up and I can't figure out what it is! Please help.

1
  • The result of json.dumps(message) and your multiline string are different byte arrays, so their digests also differ. We do not know what did you pass to the online site: new lines, spaces,... So it is hard to judge what result is expected. Commented Feb 4, 2022 at 23:16

2 Answers 2

1

It's the fault of a site. It generates wrong hmac

This site will give you expected

2383734eba9903278b5e91766fef3413f35c823090d01196ab5c682af19f4c81
Sign up to request clarification or add additional context in comments.

3 Comments

No its not. The site is correct. I am expecting beedda97cf89103141f2e44cbc6241ced093537c499887289b34d5a3ebc90e97. Python is probably messing up while encoding/decoding
@ckax i mean the 2nd google listed site gives a correct answer (the same as python does), so...
The correct signature for the json is beedda97cf89103141f2e44cbc6241ced093537c499887289b34d5a3ebc90e97. Here's another site, that produces this same result tools.chilkat.io/hmac#macResult
0

The difference between your code and the site is in the end-of-line sequence: your code is using LF (\n), and the site is using CRLF (\r\n).

Try this message:

message = '''{\r
    "fruit": "Apple",\r
    "size": "Large",\r
    "color": "Red"\r
}'''

and you will get the same result.

1 Comment

oh my god. yes. this is it. Thank you very much. I was so close I even used json.dumps(message,indent=4,separators=(",\r",": ")) but failed to figure out there's one more \r next to {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.