如何在PHP中获取C#的System.Text?

以下是C#和PHP的代码,我需要一些帮助。我正在尝试生成C#中的身份验证密钥,但希望在PHP中进行转换。一切都完成了,但我不知道如何在PHP中实现[System.Text],因为PHP中有hash_hmac(),但在同一函数中可能$string。


C# 版本


var hmac = new System.Security.Cryptography.HMACSHA256();

var buffer = userName + accessKey + timeStamp + originUrl;

var hash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(buffer));

var authenticationKey = Convert.ToBase64String(hash);

版本


$hmac = hash_hmac('sha256', $string, $buffer);

$encoded = base64_encode($hmac);

任何人都可以帮我。这将是非常有帮助的。谢谢。


白板的微信
浏览 128回答 3
3回答

慕桂英546537

我也在寻找这个,尽管它只是一个小的varibale的错误,在hash_hmac函数中将最后一个值传递给true,这将返回原始输出,当您将其转换为base64时,它将给出与c#代码相同的输出。$buffer = $userName.$accessKey.$timeStamp.$originUrl;$hmac = hash_hmac('sha256', $buffer, $tokenSecret, true);$authenticationKey = base64_encode($hmac);只需在 c# 函数中使用键,如下面的代码所示var hmac = new System.Security.Cryptography.HMACSHA256();hmac.Key = System.Text.Encoding.UTF8.GetBytes(tokenSecret);在我的代码中,我有bas64形式的tokenSecret变量。

aluckdog

在 c# 代码中,使用了随机生成的密钥。查看文档:https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.hmacsha256?view=netframework-4.8#constructorsHMACSHA256()使用随机生成的密钥初始化 HMACSHA256 类的新实例。HMACSHA256(字节[])使用指定的关键数据初始化 HMACSHA256 类的新实例现在比较php文档:https://www.php.net/manual/en/function.hash-hmac.phphash_hmac ( string $algo , string $data , string $key [, bool $raw_output = FALSE ] ) : string你看,你在php中调用buffer的东西实际上是键,你在c#中调用buffer的是你散列的数据。因此,应包含要散列的数据。$string根据转换,您不需要在php中获取字节:这个C#编码代码的PHP等效物是什么?

红颜莎娜

您可以使用解包方法获得十六进制值:$value = unpack('H*', buffer);echo $value[1];
打开App,查看更多内容
随时随地看视频慕课网APP