Nodejsencryption与Python hashlib

我试图做一个Python函数和nodejs函数计算相同的散列。 但是,好像输出的二进制文件在nodejsencryption和python hashlib之间是不同的。

我正在使用的python是:

hash = hashlib.sha512() hash.update(salt) hash.update(password.encode('utf8')) hash.digest() 

节点/咖啡文本是:

 crypto.createHash('sha512').update(salt, 'binary').update(password, 'utf8').digest() 

这些线应该产生相同的结果,但由于某些原因,他们不。 帮帮我?

他们似乎产生相同的结果,但因为节点的digest()返回一个Unicodestring,而Python的返回一个bytes对象,这可能不会立即明显:

节点0.8.11上的CoffeeScript 1.4.0:

 coffee> salt='abc' 'abc' coffee> password='def' 'def' coffee> d = crypto.createHash('sha512').update(salt, 'binary').update(password, 'utf8').digest() 'ã.ñ#èí&ezK=\u0007»v\u0018\u0006CWEVNAP §\u0003¾*}¶\u001e=9\f+¹~-L1\u001fÜiÖ±&\u0005õ© ç' 

Python 3.3.0:

 >>> salt, password=b'abc', 'def' >>> hash = hashlib.sha512() >>> hash.update(salt) >>> hash.update(password.encode('utf8')) >>> d = hash.digest() >>> print(d) b'\xe3.\xf1\x96#\xe8\xed\x9d&\x7fez\x81\x94K=\x07\xad\xbbv\x85\x18\x06\x8e\x88CWEVN\x8dAP\xa0\xa7\x03\xbe*}\x88\xb6\x1e=9\x0c+\xb9~-L1\x1f\xdci\xd6\xb1&\x7f\x05\xf5\x9a\xa9 \xe7' 

看起来很不一样,对吧? 但是,如果仔细观察,可打印的字符是相同的,那么CWEVN运行非常明显。 你可以看到更多的相似之处,如果你解码为拉丁-1 …

 >>> print(d.decode('latin1')) ã.ñ#èí&ezK=»vCWEVNAP §¾*}¶=9 +¹~-L1ÜiÖ±&õ© ç 

这是非常明显的,这是完全相同的string,它只是节点逃脱不可打印的字符。

和Python 2.7.2:

 >>> salt, password='abc', u'def' >>> hash = hashlib.sha512() >>> hash.update(salt) >>> hash.update(password.encode('utf8')) >>> d = hash.digest() >>> print(d) ?.?#??&ez??K=??v???CWEVN?AP???*}??=9 +?~-L1?iֱ&? ? >>> print(d.decode('latin1')) ã.ñ#èí&ezK=»vCWEVNAP §¾*}¶=9 +¹~-L1ÜiÖ±&õ© ç 

再次,相同的string。

鉴于我的terminal,C语言环境等都是UTF-8(这是OS X),我不知道为什么CoffeeScript解码为Latin-1。