2011-08-08 32 views
0

隨着服務提供商給了我下面的PHP代碼,我需要複製在C#將PHP的陣列和SHA1散列函數到C#

$aData = array('merchant_id'  => 'your merchant ID', // 123456 
       'project_id'  => 'your project ID', // 242342 
       'amount'   => 'amount', // 199 = 1,99 EUR 
       'currency_code' => 'currency code',  // EUR 
       'purpose_1'  => 'subject line1', 
       'merchant_key'  => 'your merchant key'); //34g1asda4524tgw 
$sHash = sha1(implode('|', $aData)); 

正如我只有非常基本的PHP知識,我會很如果有人可以幫助我將其轉換爲c#,那將非常有用。

我的第一個想法是創建一個字典,但implode函數中的管道打擾了我一下。那麼我應該使用什麼樣的數組/列表?

那我該如何「內爆」這個清單呢?

SOLUTION

由於去@andreas和@Mchl! 以下代碼返回65f23ce1507167668691445bd35451e4c6b0572b的散列。

 //test 
     string merchantId = "your merchant ID"; 
     string projectId = "your project ID"; 
     string amount = "amount"; 
     string currency = "currency code"; 
     string invoiceId = "subject line1"; 
     string merchantKey = "your merchant key"; 

     string imploded = merchantId + "|" + projectId + "|" + amount + "|" + currency + "|" + invoiceId + "|"+merchantKey; 
     byte[] arrayData = Encoding.ASCII.GetBytes(imploded); 
     byte[] hash = SHA1.ComputeHash(arrayData); 
     //return hash.ToString(); 
     string result = null; 
     string temp = null; 

     for (int i = 0; i < hash.Length; i++) 
     { 
      temp = Convert.ToString(hash[i], 16); 
      if (temp.Length == 1) 
       temp = "0" + temp; 
      result += temp; 
     } 

回答

2

它基本上調用連接數組值的sha1方法|分離:

sha1("123456|242342|199|EUR|subject1|34g1asda4524tgw");

我不是C#專家,但我想有這樣做,在C#中是微不足道的:)


這裏有你一些參考結果:

>> $aData = array('merchant_id'  => 'your merchant ID', // 123456 
..    'project_id'  => 'your project ID', // 242342 
..    'amount'   => 'amount', // 199 = 1,99 EUR 
..    'currency_code' => 'currency code',  // EUR 
..    'purpose_1'  => 'subject line1', 
..    'merchant_key'  => 'your merchant key'); //34g1asda4524tgw 

>> $aData; 
array (
    'merchant_id' => 'your merchant ID', 
    'project_id' => 'your project ID', 
    'amount' => 'amount', 
    'currency_code' => 'currency code', 
    'purpose_1' => 'subject line1', 
    'merchant_key' => 'your merchant key', 
) 

>> implode('|',$aData); 
'your merchant ID|your project ID|amount|currency code|subject line1|your merchant key' 

>> sha1(implode('|',$aData)); 
'65f23ce1507167668691445bd35451e4c6b0572b' 
+0

不是一個好主意BTW(問題提供的代碼),因爲你需要確保數組的鍵按特定的順序(這不是字母) – Mchl

+0

我同意,它會如果數組鍵是整數,那麼它會更好,因爲代碼並不真正關心密鑰,但是,這只是我給了OP的想法:) –

+0

@Mchl whoa非常感謝代碼引用。 –

0

該implode需要某種形式的有序列表。因此Dictionary<K,V>不是正確的選擇。我會去List<KeyValuePair<string,string>

您需要按照與PHP列舉它們相同的順序添加對。不知道如果這是加法或未定義,...

下一個問題是如何在這種情況下對待鍵值對。 implode的文檔沒有說明。我的例子只是使用對中的值。

string joinedString=string.Join("|", list.Value); 

接下來,您需要將字符串轉換爲字節數組。爲此,您需要選擇一種與php使用的編碼匹配的編碼,但不知道這是什麼。例如使用UTF-8:

string joinedBytes=Utf8Encoding.GetBytes(joinedString);