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