首页 > 解决方案 > 在 PHP 中复制散列 C# 算法

问题描述

有人向我提供了一个 C# 代码作为密码摘要生成的示例,我正在尝试在 PHP 代码中复制该日志。

C#脚本:

using System;
using System.Security.Cryptography;
using System.Text;

public class Program
{   
    public static void Main(){
        var password = "1234";
        var fecha = DateTime.UtcNow;
        var nonce = Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.NewGuid().ToString().Replace("-", "")));

        var nonceBytes = Convert.FromBase64String(nonce);
        var createdBytes = Encoding.UTF8.GetBytes(fecha.ToString());
        var passwordBytes = Encoding.UTF8.GetBytes(password);

        var digestBytes = new byte[nonceBytes.Length + createdBytes.Length + passwordBytes.Length];
        Array.Copy(nonceBytes, digestBytes, nonceBytes.Length);
        Array.Copy(createdBytes, 0, digestBytes, nonceBytes.Length, createdBytes.Length);
        Array.Copy(passwordBytes, 0, digestBytes, nonceBytes.Length + createdBytes.Length, passwordBytes.Length);

        var computeBytes = new SHA1Managed().ComputeHash(digestBytes);
        var digest = Convert.ToBase64String(computeBytes);

        Console.WriteLine(digest);
        Console.WriteLine(nonce);
        Console.WriteLine(fecha);
    }
}

C#转储示例:

tM/7oLWxtQL9+eeRAxWrVEOO+Bc=
ZjA5MGM4NmJlYWZlNGVjZjllYWM1YTU4ZjA3M2YyOGY=
1/17/2020 4:45:38 PM

到目前为止,我的 PHP 代码:

<?php

function gen_nonce($length = 24)
{
    return base64_encode(random_bytes($length));
    // return base64_encode(uniqid());
}

function gen_date()
{
    return gmdate("Y-m-d\TH:i:s\Z");
}

function get_bytes($value)
{
    $sha1 = sha1($value, true);
    $encoded = base64_encode($sha1);

    return $encoded;
}

function new_bytes($value)
{
    return random_bytes(strlen($value));
}

$nonce = gen_nonce();
$date = gen_date();
$password = "1234";

// $nonce_bytes = base64_decode($nonce);
// $date_bytes = get_bytes($date);
// $password_bytes = get_bytes($password);

$digest_bytes = new_bytes($nonce.$date.$password);

$digest = base64_encode(sha1($digest_bytes, true));

$result = [
    "username" => "USERNAME",
    "password" => $digest,
    "nonce" => $nonce,
    "created" => $date,
];

echo(json_encode($result));

PHP转储示例:

{"username":"USERNAME","password":"cw0LXT5Zk2\/fdU0svabD6NRobGU=","nonce":"7KQUXajiJKwUxpWATohI0GyhCLfEnUFx","created":"2020-01-17T16:59:09Z"}

我猜我的代码完全错误,因为使用此密码作为身份验证方法的 API 抛出了错误的凭据错误消息。

为了尽可能好地复制 C# 代码,我该怎么做?

提前致谢。

标签: c#php

解决方案


推荐阅读