它们似乎确实产生了相同的结果,但是由于node的digest()返回了Unicode字符串,而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运行非常明显.如果将其解码为Latin-1,您还会看到更多相似之处…
>>> print(d.decode('latin1'))
?.?#èí&ezK=??vCWEVNAP?§?*}?=9
+?~-L1?i?±&?? ?
很明显,这是完全相同的字符串,只是Node在转义不可打印的字符.
和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?±&?? ?
同样,相同的字符串.
鉴于我的终端,C语言环境等都是UTF-8(这是OS X),我不知道为什么CoffeeScript会解码为Latin-1.