Search code examples
pythonjsonpython-3.xhashhmac

Python generates wrong HMAC SHA256 signature for JSON string


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.


Solution

  • 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.