Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 897
Nguyen Tien Huy Avatar asked Jun 22 '15 07:06

Nguyen Tien Huy


1 Answers

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
like image 144
Eric Tsui Avatar answered Oct 18 '22 14:10

Eric Tsui