PHP和Node.JS中cyrillic的sha1哈希值的差异


Difference of sha1 hashes in PHP and Node.JS for cyrillic

如果我尝试从"ABC"中获得sha1,如果PHP和Node.JS,它们是相同的。

function sha1(input) {
  return crypto.createHash('sha1').update(input).digest('hex');
};

但是如果我尝试对像这样的西里尔字母进行哈希:"ЭЮЯЁ",它们不是。

如何修复?

问题可能是字符集/编码不匹配。

如果PHP中的字符串是UTF-8编码,您可以通过指定'utf8':

在Node.js中镜像该字符串。
function sha1(input) {
  return crypto.createHash('sha1').update(input, 'utf8').digest('hex');
};
> crypto.createHash('sha1').update('ЭЮЯЁ').digest('hex')
'da7f63ac9a3b5c67c8920871145cb5904f3df29a'
> crypto.createHash('sha1').update('ЭЮЯЁ', 'utf8').digest('hex')
'f78c3521413a8321231e35665f8c4a16550e182a'

'ABC'将有更好的匹配机会,因为这些都是ASCII字符,而ASCII是许多其他字符集的起点。当你使用超出ASCII的代码时,你会更经常遇到冲突