1

I'm attempting to port some NodeJS code to Python 3, but am having trouble getting a SHA1 hash to behave identically.

This code in each language shows the problem:

NodeJS

var crypto = require('crypto');
crypto.createHash('sha1');
var h = crypto.createHash('sha1');
h.update(new Buffer('pXHepU2vIdYJuIAN', 'base64').toString('binary'));
console.log(h.digest('hex')); // ea70f5b1ec762290cefd37bc0f9a7421dcc93466

Python 3

import hashlib
import base64
h = hashlib.sha1()
h.update(base64.b64decode(b'pXHepU2vIdYJuIAN'))
print(h.hexdigest()) # 74161d2d37d9fff312dd396d5f779133c4bfd88d

I think I'm passing the Python input in the wrong format as if I remove the .toString('binary') from the NodeJS code it matches.

Could anyone explain to me what the Python code should be, and why they behave differently?

1
  • Compare the data before hashing it, look for any white space or line break character as well. Commented May 18, 2017 at 5:17

1 Answer 1

1

The python code like this:

import hashlib
import base64

h = hashlib.sha1()
h.update(base64.b64decode(b'pXHepU2vIdYJuIAN').decode('latin1').encode())
print(h.hexdigest()) #result is ea70f5b1ec762290cefd37bc0f9a7421dcc93466

I have referred to this question Nodejs crypto vs python hashlib

Hope it helps you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.