dongyukui8330 2016-08-25 02:15
浏览 82
已采纳

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

got a problem with converting python to php. I've got the following code in 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 is the following array:

[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]


I already converted it to 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;
}

But the returned array $sha looks like this one:

[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]

Maybe some of you will find my mistake?

展开全部

  • 写回答

1条回答 默认 最新

  • ds34222 2016-08-25 02:37
    关注

    I saw few errors in your PHP code.

    This is a python snippet:

    >>> 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]
    

    And the PHP version, corrected:

    $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]
    

    In your PHP version, $sha = hash_update($sha, $user); was bad because 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 with the last parameter (raw_output) to true to get binary data.

    Last error, using openssl_digest on the SHA result's was computing the digest of the SHA digest's. Funny, isn't it? :).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部