簡體   English   中英

c#md5和php md5不匹配

[英]c# md5 and php md5 not match

這是我的C#計算簽名代碼

using System;
using System.Text;

public class Test
{
    public static void Main()
    {
    string str;
    string syskey = "123456789";
    str = GenSignature(syskey,"foo","20170426001757");
    Console.WriteLine(str);
}

public static string GenSignature(string syskey,params string[] paramValues)
    {
        string source = "";
        for (int i = 0; i < paramValues.Length; i++)
        {
            if (!string.IsNullOrEmpty(paramValues[i]))
            {
                source += (string.IsNullOrEmpty(source) ? "" : "&") + paramValues[i];
            }
        }

        if (string.IsNullOrEmpty(source))
        {
            return "";
        }

        source +=  "&" + syskey;
        // Debug.WriteLine(source);
        using (System.Security.Cryptography.MD5 m = System.Security.Cryptography.MD5.Create())
        {
            byte[] hashData = m.ComputeHash(UTF8Encoding.UTF8.GetBytes(source));
            return BitConverter.ToString(hashData).Replace("-", "").ToUpper();
        }
    }
}

和PHP獲取簽名代碼如下:

function getSignature() {
    $syskey = "123456789";
    $sysCode =  "foo";
    $timeStamp = "20170426001757";
    $str = "&".$sysCode."&".$timeStamp."&".$syskey;
    return strtoupper(md5($str));
}
echo getSignature();

我對C#不太了解,但是得到的結果卻完全不同,是否有人知道這兩種語言並告訴我一些東西,非常感謝。

在PHP示例中,每個部分都用&符( & )開頭,但是在C#版本中,除了第一個部分之外,其他每個部分都附加了前綴:

source += (string.IsNullOrEmpty(source) ? "" : "&") + paramValues[i];

自從最初將source設置為""以來, string.IsNullOrEmpty(source)將首次返回true ,因此不會在字符串的開頭添加與號。

更改您的代碼,它應該可以工作:

source += "&" + paramValues[i];

在線測試: https//dotnetfiddle.net/KhoFtL

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM