在您的 C# 应用程序中,您以两种不同的方式生成 byte[] 数组,结果略有不同。您的 PHP 脚本需要准确地模拟它们。
hash.Key = HexToByte(encryptionKey)
你传入一个 16 个字符长的字符串并得到一个 8 个字节的数组,就像
hash.Key = new byte[]{0xAE, 0x09, 0xF7, 0x2B, 0x00, 0x7C, 0xAA, 0xB5 };
但是
string password = "pa55w0rd";
byte[] b = Encoding.Unicode.GetBytes(password)
由于 Encoding.Unicode,返回一个包含 16 个元素的数组,例如在您的 php 脚本中,您可以使用
$data = mb_convert_encoding($password, 'UTF16-LE')byte[] b = { 0x112, 0x0, 0x97, 0x0, 0x53, 0x0, 0x53, 0x0, 0x119, 0x0, 0x48, 0x0, 0x114, 0x0,0x100, 0x0 }
将
$password 的编码更改为 utf-16le以实现类似的结果. hash_hmac() 不知道任何编码会将字符串视为 16 字节单字节编码字符串,就像 .net 中的 hash.ComputeHash(byte[]) 一样。
<?php
$password = "pa55w0rd";
$key = HexToBytes("AE09F72B007CAAB5"); // 8 bytes, hex
// $to must be 'UTF-16LE'
// $from depends on the "source" of $password
$data = mb_convert_encoding($password, 'UTF-16LE', 'ASCII');
// I've saved this script as an ascii file -> the string literal is ASCII encoded
// therefore php's strlen() returns 8 for $password and 16 for $data
// this may differ in your case, e.g. if the contents of $password comes from a
// http-request where the data is utf-8 encoded. Adjust the $from parameter for
// mb_convert_encoding() accordingly
echo 'Debug: |data|=', strlen($data), ' |password|=', strlen($password), "\n";
$h = HexToBytes(hash_hmac('sha1', $data, $key));
echo 'hmac-sha1: ', base64_encode($h);
function HexToBytes($s) {
// there has to be a more elegant way...
return join('', array_map('chr', array_map('hexdec', str_split($s, 2))));
}
印刷
调试:|数据|=16 |密码|=8
hmac-sha1: ok9NOVhpTkxLoLfvh1430SFb5gw=