我想将以下C#代码转换为PHP.
C#是:
byte[] operation = UTF8Encoding.UTF8.GetBytes("getfaqs");
byte[] secret = UTF8Encoding.UTF8.GetBytes("Password");
var hmac = newHMACSHA256(secret);
byte[] hash = hmac.ComputeHash(operation);
Run Code Online (Sandbox Code Playgroud)
我已经变成了这个:
$hash = hash_hmac( "sha256", utf8_encode("getfaqs"), utf8_encode("Password"));
Run Code Online (Sandbox Code Playgroud)
然后我有:
var apiKey = "ABC-DEF1234";
var authInfo = apiKey + ":" + hash
//base64 encode the authorisation info
var authorisationHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(authInfo));
Run Code Online (Sandbox Code Playgroud)
我认为应该是:
$authInfo = base64_encode($apiKey . ":" . $hash);
Run Code Online (Sandbox Code Playgroud)
要么
$authInfo = base64_encode(utf8_encode($apiKey . ":" . $hash));
Run Code Online (Sandbox Code Playgroud)
但不确定,请注意第二个编码使用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 );
Run Code Online (Sandbox Code Playgroud)
此外,字符串连接运算符是.,所以:
$authInfo = base64_encode($apiKey . ":" . $hash);
Run Code Online (Sandbox Code Playgroud)