为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
白板的微信 2022-09-03 16:40:34
以下是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);任何人都可以帮我。这将是非常有帮助的。谢谢。
查看完整描述

3 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

我也在寻找这个,尽管它只是一个小的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变量。


查看完整回答
反对 回复 2022-09-03
?
aluckdog

TA贡献1847条经验 获得超7个赞

在 c# 代码中,使用了随机生成的密钥。查看文档:https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.hmacsha256?view=netframework-4.8#constructors

HMACSHA256()

使用随机生成的密钥初始化 HMACSHA256 类的新实例。

HMACSHA256(字节[])

使用指定的关键数据初始化 HMACSHA256 类的新实例

现在比较php文档:https://www.php.net/manual/en/function.hash-hmac.php

hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = FALSE ] ) : string

你看,你在php中调用buffer的东西实际上是键,你在c#中调用buffer的是你散列的数据。

因此,应包含要散列的数据。$string

根据转换,您不需要在php中获取字节:这个C#编码代码的PHP等效物是什么?


查看完整回答
反对 回复 2022-09-03
?
红颜莎娜

TA贡献1842条经验 获得超13个赞

您可以使用解包方法获得十六进制值:


$value = unpack('H*', buffer);

echo $value[1];


查看完整回答
反对 回复 2022-09-03
  • 3 回答
  • 0 关注
  • 127 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号