试图为api创建PHP等效的C#签名哈希方法

我正在尝试复制一个c#方法来生成签名哈希以与API通信,在基于我给出的c#方法示例的
PHP中复制相同的示例结果时遇到了麻烦.

我正在尝试做的单词问题版本是:(来自api文档)

计算请求签名

请求签名,具有SHA-1哈希码的HMAC,通过按顺序连接Service,Method和Timestamp参数的值,然后使用秘密访问密钥计算符合RFC 2104的HMAC来计算钥匙”.计算的HMAC值必须是base64编码的

测试数据:

service_name = “Zoyto Fulfillment Service”
timestamp: “2010-07-21T04:33:55Z”
api_secret = “2c0774063f4bb1a10ca39ba6c806636a57d78dc3”
method = “getOrderStatus”

Result should be:
signature: “mlePFDcrTAxd+PWA6hOGGtvu2Zc=”

我有一个c#方法的代码示例,用于创建签名哈希以进行API调用:

public string createSignature(string api_secret, string method, string timestamp, string service_name) { 
  DateTime currentTime = DateTime.UtcNow; string toSign = service_name.ToLower() +   method.ToLower() + timestamp.ToLower(); 
  byte[] toSignBytes = Encoding.UTF8.GetBytes(toSign); byte[] secretBytes = Encoding.UTF8.GetBytes(api_secret); 
  HMAC signer = new HMACSHA1(secretBytes byte[] sigBytes = signer.ComputeHash(toSignBytes); 
  string signature = Convert.ToBase64String(sigBytes); 
  return signature; 
}

目前,我的php方法如下:

$testSecret = '2c0774063f4bb1a10ca39ba6c806636a57d78dc3';
$testSvc    = 'Zoyto Fulfillment Service';
$testStamp  = strtotime('2010-07-21 04:33:55');   
$method = 'getOrderStatus';

$sig    = utf8_encode($testSvc.$method.$testStamp);

$hash   = hash_hmac("sha1", $sig, $testSecret, true);

$sig    = base64_encode($hash);
return $sig;

//returns:
//OUhgiIqxngaFm1Rquxm1lZ/3CzE=

任何帮助表示赞赏

最佳答案 我不确定你从哪里获得C#代码,但它不起作用.此PHP代码将为您提供所需输入的所需输入.

function createSignature($api_secret, $method, $timestamp, $service_name) {
    $toSign = strtolower($service_name) . strtolower($method) . strtolower($timestamp);
    $sig = hash_hmac('sha1', $toSign, $api_secret, true);
    return base64_encode($sig);
}

$api_secret = '2c0774063f4bb1a10ca39ba6c806636a57d78dc3';
$method = 'getOrderStatus';
$timestamp  = '2010-07-21T04:33:55Z'; 
$service_name    = 'Zoyto Fulfillment Service';

echo createSignature($api_secret, $method, $timestamp, $service_name);
// output: mlePFDcrTAxd+PWA6hOGGtvu2Zc=

注意:需要PHP 5> = 5.1.2或PECL哈希> = 1.1

点赞