简体   繁体   English

openssl hmac与python hmac不同

[英]openssl hmac differ from python hmac

with: 有:

KEY='7vgd39eyxald9sucClM7'
DATA='POST\nmultipart/form-data\nWed, 10 Jun 2015 07:27:43 GMT\n/1/classes/item\nx-wbs-uid:f886a495220975d724ff3679a5cc9cef04343076'

in command line 在命令行中

HASH_BIN=`echo -n "$DATA" | openssl dgst -sha256 -mac HMAC -macopt key:$KEY -binary`
openssl enc -e -base64 <<< $HASH_BIN
result: VmBdzRcNg0OJZVVLSgg1zcViflug9iqtb6Gsnjqf9F8K

in python 在python中

import hmac, hashlib, base64
hash = hmac.new(KEY, DATA, hashlib.sha256).digest()
base64.encodestring(hash).strip()
result: u6Poj7Jqrz6+wvXDNyK88pVm5iKUF6RUmq2P2LtHmuE=

Can someone give me a help??? 有人可以给我一个帮助吗? Thanks a lot. 非常感谢。

It should be caused by the DATA string definition in your python code. 它应该是由python代码中的DATA字符串定义引起的。

You need add r to treat the DATA as a raw string, such as 您需要添加r以将DATA视为原始字符串,例如

DATA=r'POST\nmultipart/form-data\nWed, 10 Jun 2015 07:27:43 GMT\n/1/classes...'

With the r , all escape codes in DATA will be ignored. 使用r ,将忽略DATA所有转义码。 That is to say, '\\n' will be treated as a newline character, but r'\\n' will be treated as the characters \\ followed by n. 也就是说,'\\ n'将被视为换行符,但r'\\ n'将被视为字符\\后跟n。 In Python, 在Python中,

'\n'  // 0x0d

r'\n' // 0x5c 0x6e 

With the r , it will output the result equals to output via openssl, 使用r ,它将输出结果等于通过openssl输出,

VmBdzRcNg0OJZVVLSgg1zcViflug9iqtb6Gsnjqf9F8K

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM