c# - 在 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# 代码,我该怎么做?
提前致谢。
解决方案
推荐阅读
- java - 找不到我的班级的编解码器 (CodecConfigurationException)
- c++ - 访问内联汇编中的 thread_local 变量
- scala - 如何在 Map[String, Dataframe] 中存储多个 Dataframes 并使用 map 的 key 访问每个 dataframe
- laravel - 如何从 laravel 查询结果中删除项目并获取它?
- javascript - 是否可以更改 WebSocket 连接上的 URL 请求?
- docker - WSO2 API 正在向 172.17.0.2 发送请求,这是 Docker 内部 IP
- python - TensorFlow 和 Anaconda 的 ModuleNotFoundError (Windows 10)
- ios - Nativescript - ReferenceError: FIRAuth
- c# - 基于日期范围的 NReco 过滤立方体
- java - 函数在某些情况下可以工作,但当最长的子字符串“重用”一个字符时会失败