将php数组和sha1哈希函数转换为c#


Convert php array and sha1 hashing function to c#

服务提供商给了我以下php代码,我需要在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#,我会非常感激。

我的第一个想法是创建一个字典,但是内爆函数中的管道有点困扰我。那么我应该使用什么样的数组/列表呢?

那么我该如何"内爆"这个列表呢?

<

解决方案/strong>

感谢@andreas和@ mcl !下面的代码返回一个哈希值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;
        }

它基本上是对连接的数组值调用sha1方法| separated:

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'

内爆需要某种形式的有序列表。因此,Dictionary<K,V>不是正确的选择。我选List<KeyValuePair<string,string>

您需要按照php枚举它们的顺序添加它们。不知道这是加法顺序还是未定义,…

下一个问题是php在这种情况下如何处理键值对。implode的文档没有说明这一点。我的示例只使用pair中的值。

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

接下来需要将字符串转换为字节数组。为此,您需要选择一种与php使用的编码相匹配的编码,但不知道是哪种编码。例如使用UTF-8:

string joinedBytes=Utf8Encoding.GetBytes(joinedString);