PHP散列('sha256', 'x')与bash命令不匹配


Having issues with PHP hash('sha256', 'x') not matching a bash command

如何使用PHP的hash()函数执行以下操作?我试过了,失败了(见更低的php代码)

echo -n '807542FB6685F9FD8F37D56FAF62F0BB4563684A51539E4B26F0840DB361E0027C' | xxd -r -p | sha256sum -b

上面的bash行输出如下:

7DE4708EB23AB611371BB778FC0C8BDE80394AB2D8704D7129FB5771E2F1730D

这段php代码做不到:

<?php
echo hash('sha256', '807542FB6685F9FD8F37D56FAF62F0BB4563684A51539E4B26F0840DB361E0027C');

输出:

e50f2ac6f7b6a2cbf640f44806affe06a330eb655f9e97bf70d5e09274340e4b

你的代码的问题是你错过了php等效的xxd -r。您可以通过使用pack("H*", $string):

来获得它。
echo hash('sha256', pack("H*", '807542FB6685F9FD8F37D56FAF62F0BB4563684A51539E4B26F0840DB361E0027C'));

或者,如果你有PHP 5.4或更高版本,你可以使用hex2bin():

echo hash('sha256', hex2bin('807542FB6685F9FD8F37D56FAF62F0BB4563684A51539E4B26F0840DB361E0027C'));

这两个的输出是:

7 de4708eb23ab611371bb778fc0c8bde80394ab2d8704d7129fb5771e2f1730d