2017-03-31 37 views
-2

我一直在努力,試圖獲得一個C#相當於一個PHP API,我得到的錯誤消息是無效的哈希值,所以我決定拆分代碼並檢查PHP和C#的單獨部分的輸出。 下面是我的了:如何從C#中獲得相同的PHP哈希值

代碼和出把PHP參考的:

$ref = time().mt_rand(0,9999999); 

----Out put as at the time it was tested---- 
14909496966594256 

在對裁判我的C#代碼如下:

string refl = (DateTime.UtcNow .Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0))).TotalSeconds + rnd.Next(0, 9999999).ToString(); 

----Out put as at the time it was tested---- 

1490602845.686821282389 

PHP的散列出同放以下變量如下:

$task = 'pay'; 
$merchant_email_on_voguepay = '[email protected]'; 
$ref = '14909496966594256'; 
$command_api_token = '9ufkS6FJffGplu9t7uq6XPPVQXBpHbaN'; 
$hash = hash('sha512',$command_api_token.$task.$merchant_email_on_voguepay.$ref); 

----Out put ---- 
1cee97da4c0b742b6d5cdc463914fe07c04c6aff8d999fb7ce7aaa05076ea17577752ecf8947e5b98e7305ef09e0de2fed73e4817d906d6b123e54c1f9b15e74 

然後C#輸出使用相同的變量iables和相同的PHP裁判出來把

const string task = "Pay"; 
const string command_api_token = "9ufkS6FJffGplu9t7uq6XPPVQXBpHbaN"; 
const string merchant_email_on_voguepay = "[email protected]"; 

    Random rnd = new Random(); 
    string refl = "14909496966594256"; 
    string hash_target = (command_api_token + task + merchant_email_on_voguepay + refl); 

    SHA512 sha512 = new System.Security.Cryptography.SHA512Managed(); 

    var bytes = UTF8Encoding.UTF8.GetBytes(hash_target); 
    string cryString = BitConverter.ToString(sha512.ComputeHash(bytes)); 
    string hashD = (cryString).Replace("-", string.Empty).ToLower(); 

    ----Out put ---- 
551b057b64f49fc6bd7d428a8e3c36ddaab5e468fd5f9042ad5d4a4fa50349e5312ad2097b4e46d1e74a5a3f4e843848352edb0ea7073dd1cd53b1c4c14ab286 

在這裏,我發現了就把我的C#是從PHP的不同。所以我的代碼可能會出現什麼問題,我想用相同的變量來獲得與php相同的結果。

任何解決此問題的好主意都是值得歡迎的。

+2

您不能在兩個不同的地方同時生成相同的隨機數。 –

+0

以及php:'mt_rand'(一個mersenne twister類型生成器)和Microsoft.NET'Random',一個基於Knuth-subtractive的例程並不完全相同。這意味着即使使用相同的種子,它們也不會創建相同的序列。兩者都不推薦用於密碼學,因爲它們太可預測。 – dlatikay

回答

2

在你的C#代碼的task"Pay"。 在PHP代碼中它是"pay"

不同的輸入值會,自然也不能散列相同。

+0

確實是這個問題,我改變了「支付」到「支付」,我得到了同樣的輸出 –