需要以下SQL HashBytes函数的C#等效项 [英] Need C# equivalent for the below SQL HashBytes function
问题描述
我已经在sql中使用以下函数创建了哈希值
I have created hash value using below function in sql
SQL查询
Select hashbytes('MD5', PNumber+CONVERT(VARCHAR(50),cast(datestamp as binary),1))
From dbo.Events
现在,我需要获取等效的C#函数以获取哈希值并将其传递给存储过程.
Now I need to get the equivalent C# function in order to get the hash value and pass it to a stored procedure.
我正在使用以下代码来获取c#等效项.但是值不匹配
I am using below code to get the c# equivalent. But values are not matching
C#代码
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;
}
以下是测试结果:
从SQL Server:
From SQL Server:
PNumber ='4272535529'
DateStamp ='2016-06-30 12:19:35.257961'
HashValue : 0x104E09499B76CB59420AEEEDBBE187F8
在C#中,我从数据库字段值中获取值,如下所示:
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
从C#GetMD5Hash函数中,我得到如下值
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
任何建议将不胜感激.
推荐答案
在C#中,看来DateTime ToString()的格式更像这样:
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.
在sql server上,您看起来也像在散列以下内容:
Also it looks like on sql server you're hashing something like:
select '12313135' + CONVERT(VARCHAR(50),cast(sysdatetime() as binary),1)
//------------
123131350x077B7127E688B23B0B000000000000000000000000000000
另一个问题可能是:
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.
这篇关于需要以下SQL HashBytes函数的C#等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!