Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get digest representation of CryptoJS.HmacSHA256 in JS

I have to generate string representation of CryptoJS.HmacSHA256 in digest (bytes representation).

I need it because i have to duplicate python code which generate such digest in javascript:

print hmac.new("secret", "test", hashlib.sha256).digest()

')�kb��>�y+������:�o��H�   '

The goal is to duplicate behaviour of code above in javascript.

Could you please suggest me how to do this?

like image 239
Andriy Ivaneyko Avatar asked Apr 03 '15 12:04

Andriy Ivaneyko


1 Answers

You can't simply send bytes to JavaScript. You need to convert this to a textual representation for it to be comparable. Hex encoding is supported by both python's hmac module and CryptoJS.

CryptoJS:

CryptoJS.HmacSHA256("test", "secret").toString(CryptoJS.enc.Hex)

Python:

hmac.new("secret", "test", hashlib.sha256).hexdigest()

Note the difference in the argument ordering.

Both produce

0329a06b62cd16b33eb6792be8c60b158d89a2ee3a876fce9a881ebb488c0914
like image 94
Artjom B. Avatar answered Nov 08 '22 01:11

Artjom B.