这个C#编码代码的PHP等价物是什么?

前端之家收集整理的这篇文章主要介绍了这个C#编码代码的PHP等价物是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将以下C#代码转换为 PHP.

C#是:

byte[] operation = UTF8Encoding.UTF8.GetBytes("getfaqs");
byte[] secret = UTF8Encoding.UTF8.GetBytes("Password");

var hmac = newHMACSHA256(secret);
byte[] hash = hmac.ComputeHash(operation);

我已经变成了这个:

$hash = hash_hmac( "sha256",utf8_encode("getfaqs"),utf8_encode("Password"));

然后我有:

var apiKey = "ABC-DEF1234";
var authInfo = apiKey + ":" + hash

//base64 encode the authorisation info
var authorisationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));

我认为应该是:

$authInfo = base64_encode($apiKey . ":" . $hash);

要么

$authInfo = base64_encode(utf8_encode($apiKey . ":" . $hash));

但不确定,请注意第二个编码使用Encoding.UTF8,而不是UTF8Encoding.UTF8.

PHP代码应该是什么样的?

解决方法

PHP字符串已经(种类)byte [],PHP没有任何编码意识. utf8_encode实际上将ISO-8859-1变为UTF-8,所以这里不需要它.

如果这些字符串是文件中的文字,则该文件只需要以UTF-8编码保存.

将true传递给hash_hmac作为第4个参数并删除那些utf8_encode调用

$hash = hash_hmac( "sha256","getfaqs","Password",true );

此外,字符串连接运算符是.,所以:

$authInfo = base64_encode($apiKey . ":" . $hash);

猜你在找的C#相关文章