Tom B Tom B - 4 months ago 21
Python Question

Porting python hash digest to node js

I'm trying to port a Python script to Node and I've become stuck on SHA1 hashes.

The following Python code:

import hashlib

user = 'test'

ret = hashlib.sha1(user.encode('utf-8')).digest()
print(ret);


Prints out:

b'\xa9J\x8f\xe5\xcc\xb1\x9b\xa6\x1cL\x08s\xd3\x91\xe9\x87\x98/\xbb\xd3'


I need a SHA1 hash in this format in Node. This Javascript:

var crypto = require('crypto');

var generator = crypto.createHash('sha1');
generator.update(new Buffer('test'));
console.log(generator.digest('binary'));


prints

©Jå̱sÓé/»Ó


How can I get Node to produce the output in the same style as Python does? It's clearly not binary or hex, what format is the python output in?

Answer

Both results are the same already. The string representation of bytes (the stuff you see on the console) differs in JavaScript and Python though. To prove that they're identical, convert both to an integer list:

> var crypto = require('crypto');
> var generator = crypto.createHash('sha1');
> generator.update(new Buffer('test'));
> var digest = generator.digest('binary');
> var lst = [];
> for (let i = 0;i < digest.length;i++) st.push(digest.charCodeAt(i));
> console.log(JSON.stringify(lst));
[169,74,143,229,204,177,155,166,28,76,8,115,211,145,233,135,152,47,187,211]

Same result in python:

>>> import hashlib, base64
>>> ret = hashlib.sha1('test'.encode('utf-8')).digest()
>>> print(list(ret))
[169, 74, 143, 229, 204, 177, 155, 166, 28, 76, 8, 115, 211, 145, 233, 135, 152, 47, 187, 211]

You can use hexdigest/digest('hex') to get a hexadecimal string ('a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'), which may be easier to handle.

But there's nothing wrong with the bytes; again, it's just the string representation that's different. For instance, if you write both bytes to a file, then both files will be totally identical.