将带有 sha 的 python 代码转换为 php

Convert python code with sha to php

在将 python 转换为 php 时遇到问题。我在 python 中有以下代码:

user = "DdrkmK5uFKmaaeNqfqReMADSUJ4sVSLrV2A8Bvs8"
passing = "K9hvwANSBW5tLYzuWptWMByTtzZZKHzm"

sha = hashlib.sha256()
sha.update(user)
sha.update(passing)
sha_A = [ord(x) for x in sha.digest()]

sha_A 是以下数组:

[231, 13, 239, 136, 20, 198, 76, 121, 67, 163, 251, 153, 114, 13, 65, 203, 41, 37, 64, 168, 43, 69, 81、103、235、161、15、58、82、57、217、178]


我已经把它转换成php:

$user = "DdrkmK5uFKmaaeNqfqReMADSUJ4sVSLrV2A8Bvs8";
$passing = "K9hvwANSBW5tLYzuWptWMByTtzZZKHzm"

$sha = hash_init("sha256");
$sha = hash_update($sha, $user);
$sha = hash_update($sha, $passing);

$sha_A = [];
$i = 0;
$digest = openssl_digest($sha, "sha256");
$digest = str_split($digest);
foreach ($digest as $x) {
  $sha_A[$i] = ord($x);
  $i = $i + 1;
}

但是返回的数组 $sha 看起来像这样:

[101, 51, 98, 48, 99, 52, 52, 50, 57, 56, 102, 99, 49, 99, 49, 52, 57, 97, 102, 98, 102, 52, 99, 56, 57, 57, 54, 102, 98, 57, 50, 52]

也许你们中的一些人会发现我的错误?

我在您的 PHP 代码中发现了一些错误。

这是一个 python 片段:

>>> sha = hashlib.sha256()
>>> sha.update(user)
>>> sha.update(passing)
>>> sha_A = [ord(x) for x in sha.digest()]
[135, 146, 107, 215, 70, 126, 179, 21, 19, 177, 191, 236, 182, 136, 192, 53, 148, 42, 160, 24, 63, 224, 170, 211, 32, 131, 59, 146, 60, 162, 77, 2]

和 PHP 版本,更正:

$ctx = hash_init('sha256');
hash_update($ctx, $user);
hash_update($ctx, $passing);
$digest = hash_final($ctx, true);

$sha_A = [];
foreach (str_split($digest) as $x) {
    $sha_A[] = ord($x);
}
[135, 146, 107, 215, 70, 126, 179, 21, 19, 177, 191, 236, 182, 136, 192, 53, 148, 42, 160, 24, 63, 224, 170, 211, 32, 131, 59, 146, 60, 162, 77, 2]

在您的 PHP 版本中,$sha = hash_update($sha, $user); 很糟糕,因为 hash_update returns a boolean. The first argument is called the context and is the result of hash_init, the second one is the data to hash. Finally, you call hash_final 使用最后一个参数 (raw_output) 到 true 来获取二进制数据。

最后一个错误,在 SHA 结果上使用 openssl_digest 计算 SHA 摘要的摘要。很有趣,不是吗? :).