2013-12-18 70 views
0

我需要將一些C#代碼轉換爲與PHP Web API等效的PHP代碼。他們的所有例子都在C#中。我認爲我有相同的PHP函數,但是我的SOAP請求返回'錯誤請求'或'未經授權 - 無效的API密鑰' - 而API頁面上的示例頁面與我的密鑰一起工作,並且請求URL看起來與摘要消息正在傳遞。 API和客戶端ID絕對正確。將C#sha256 hashing轉換爲PHP等效

下面是C#代碼:

private string GenerateDigest(long currentTime) 
    { 
     SHA256Managed hashString = new SHA256Managed(); 
     StringBuilder hex = new StringBuilder(); 
     byte[] hashValue = hashString.ComputeHash(Encoding.UTF8.GetBytes(String.Format("{0}{1}", currentTime, txtApiKey.Text))); 

     foreach (byte x in hashValue) 
     { 
      hex.AppendFormat("{0:x2}", x); 
     } 

     return hex.ToString(); 
    } 

這裏是我寫的嘗試做C#是做PHP函數:

public static function generateDigest($api_key) { 
    return hash('sha256', time() . mb_convert_encoding($api_key, 'UTF-8')); 
} 

我不是很精通C#,所以我承擔我出錯的地方是它在做hex.AppendFormat()。我不知道這應該是在PHP中。最終的結果是被附加到URL,以生成SOAP請求的散列,例如:

https://payments.homeaway.com/tokens?time=1387385872013 &消化= 1bd70217d02ecc1398a1c90b2be733ff686b13489d9d5b1229461c8aab6e6844 &的clientId = [刪除]

編輯:

這是在C#中傳遞的currentTime變量。

// Request validation setup 
TimeSpan timeSinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1); 
long currentTime = (long)timeSinceEpoch.TotalMilliseconds; 
string digest = GenerateDigest(currentTime); 
+0

爲什麼'currentTime'是'long'?它是一個時間戳,例如'time()'產生的時間戳? – Jon

+0

用currentTime更新答案。 – Kevin

回答

0

我在這裏同樣的問題coverting這PHP代碼是我的代碼來解決這個問題:如果有人正在尋找這個答案有時間做

function generateDigest($time, $api_key) { 
    $hash = hash('sha256', $time . mb_convert_encoding($api_key, 'UTF-8'), true); 
    return $this->hexToStr($hash); 
} 

function hexToStr($string){ 
    //return bin2hex($string); 
    $hex=""; 
    for ($i=0; $i < strlen($string); $i++) 
    { 
     if (ord($string[$i])<16) 
      $hex .= "0"; 
     $hex .= dechex(ord($string[$i])); 
    } 
    return ($hex); 
} 
0

。 PHP的time()函數返回C#中的調用返回毫秒數的時間,以秒爲單位。

因此,爲了得到$currentTime正確的做法是

$currentTime = time() * 1000; 

這已經與API測試。