问题
here is my c# compute signature code
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();
}
}
}
and the php get signature code is below:
function getSignature() {
$syskey = "123456789";
$sysCode = "foo";
$timeStamp = "20170426001757";
$str = "&".$sysCode."&".$timeStamp."&".$syskey;
return strtoupper(md5($str));
}
echo getSignature();
I do not know c# very well, but the result I get are totally different, Did any one know the two languages and tell me something, Thanks a lot.
回答1:
In the PHP example you prepend every part with an ampersand (&
), however in the C# version you prepend every part but the first:
source += (string.IsNullOrEmpty(source) ? "" : "&") + paramValues[i];
string.IsNullOrEmpty(source)
will return true
the first time since you initially set source
to ""
, thus an ampersand won't get added in the very beginning of the string.
Change your code to this and it should work:
source += "&" + paramValues[i];
Online test: https://dotnetfiddle.net/KhoFtL
来源:https://stackoverflow.com/questions/43650593/c-sharp-md5-and-php-md5-not-match