How to get digest representation of CryptoJS.HmacSHA256 in JS

Andriy Ivaneyko picture Andriy Ivaneyko · Apr 3, 2015 · Viewed 20.8k times · Source

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?

Answer

Artjom B. picture Artjom B. · Apr 3, 2015

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