[英]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. 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遵循 python 代码。
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
.我期待
beedda97cf89103141f2e44cbc6241ced093537c499887289b34d5a3ebc90e97
但我得到2383734eba9903278b5e91766fef3413f35c823090d01196ab5c682af19f4c81
If I read the JSON file directly, I get a signature different from both.如果我直接读取 JSON 文件,我会得到一个不同于两者的签名。 But according to my use case, I can't read the JSON file as such.
但根据我的用例,我无法读取 JSON 文件。 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 .我可以通过这个网站https://www.freeformatter.com/hmac-generator.html和这个https#macchit . I think some formatting/encoding is getting messed up and I can't figure out what it is.
我认为某些格式/编码变得混乱,我无法弄清楚它是什么。 Please help.
请帮忙。
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
).您的代码和站点之间的区别在于行尾序列:您的代码使用 LF (
\n
),而站点使用 CRLF ( \r\n
)。
Try this message:试试这个消息:
message = '''{\r
"fruit": "Apple",\r
"size": "Large",\r
"color": "Red"\r
}'''
and you will get the same result.你会得到同样的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.