openssl hmac differ from python hmac

3k views Asked by At

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

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.

1

There are 1 answers

0
Eric Tsui On

It should be caused by the DATA string definition in your python code.

You need add r to treat the DATA as a raw string, such as

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. That is to say, '\n' will be treated as a newline character, but r'\n' will be treated as the characters \ followed by n. In Python,

'\n'  // 0x0d

r'\n' // 0x5c 0x6e 

With the r, it will output the result equals to output via openssl,

VmBdzRcNg0OJZVVLSgg1zcViflug9iqtb6Gsnjqf9F8K