【问题标题】:c# md5 and php md5 not matchc# md5和php md5不匹配
【发布时间】:2017-04-27 15:14:31
【问题描述】:

这是我的 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#不是很了解,但是得到的结果完全不同,有没有人知道这两种语言并告诉我一些事情,非常感谢。

【问题讨论】:

    标签: c# php md5


    【解决方案1】:

    在 PHP 示例中,您在每个部分前面加上一个 & 符号 (&amp;),但在 C# 版本中,您在除第一个部分之外的每个部分前面添加:

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

    string.IsNullOrEmpty(source) 将在您最初将source 设置为"" 后第一次返回true,因此不会在字符串的开头添加与号。

    将您的代码更改为此,它应该可以工作:

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

    在线测试:https://dotnetfiddle.net/KhoFtL

    【讨论】:

    • 好的,现在可以了,我花了将近一天的时间,觉得有点复杂,非常感谢您的帮助
    • @gy134340 :很高兴我能帮上忙!请按我帖子左侧的勾号/复选标记将我的答案标记为“已接受”。欲了解更多信息,请参阅:How does accepting an answer work?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多