Need C# equivalent for the below SQL HashBytes fun

2019-07-12 13:43发布

I have created hash value using below function in sql

SQL query

Select hashbytes('MD5', PNumber+CONVERT(VARCHAR(50),cast(datestamp as  binary),1))   
From dbo.Events

Now I need to get the equivalent C# function in order to get the hash value and pass it to a stored procedure.

I am using below code to get the c# equivalent. But values are not matching

C# Code

var strDate = policyEventFromQueue.DateStamp.ToString();
var binaryvalue = Encoding.Unicode.GetBytes(strDate);
var hashkey = GetMD5Hash(PNumber + binaryvalue);

public static byte[] GetMD5Hash(string input)
{
    System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] bs = System.Text.Encoding.Unicode.GetBytes(input);

    bs = x.ComputeHash(bs);
    return bs;
}

Here are test results:

From SQL Server:

PNumber ='4272535529'
DateStamp ='2016-06-30 12:19:35.257961'

HashValue : 0x104E09499B76CB59420AEEEDBBE187F8

In C# I am getting the value from DB Field value as below

[0]: 16
[1]: 78
[2]: 9
[3]: 73
[4]: 155
[5]: 118
[6]: 203
[7]: 89
[8]: 66
[9]: 10
[10]: 238
[11]: 237
[12]: 187
[13]: 225
[14]: 135
[15]: 248

From C# GetMD5Hash Function i am getting value as below

[0]: 30
[1]: 153
[2]: 105
[3]: 203
[4]: 34
[5]: 124
[6]: 20
[7]: 12
[8]: 207
[9]: 113
[10]: 210
[11]: 144
[12]: 18
[13]: 145
[14]: 22
[15]: 36

Any suggestion will be appreciated.

1条回答
啃猪蹄的小仙女
2楼-- · 2019-07-12 14:28

In c# it looks like the format for a DateTime ToString() is more like this:

DateTime.Now.ToString()
//--------
"8/3/2016 4:11:14 PM"

I think you're hashing two different strings. For the hashes to match you'll need to format the dates the same before computing the hash value.

Also it looks like on sql server you're hashing something like:

select '12313135' + CONVERT(VARCHAR(50),cast(sysdatetime() as  binary),1)
//------------
123131350x077B7127E688B23B0B000000000000000000000000000000

Another issue could be this:

var binaryvalue = Encoding.Unicode.GetBytes(DateTime.Now.ToString());
var hashkey = "123456" + binaryvalue;
Console.WriteLine(hashkey)
//----------
123456System.Byte[]

your conversions between strings and bytes is off.

查看更多
登录 后发表回答