Need C# equivalent for the below SQL HashBytes function

核能气质少年 提交于 2019-12-10 22:51:29

问题


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:


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.



来源:https://stackoverflow.com/questions/38746623/need-c-sharp-equivalent-for-the-below-sql-hashbytes-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!