gpt4 book ai didi

c# - 下面的 SQL HashBytes 函数需要 C# 等价物

转载 作者:搜寻专家 更新时间:2023-10-30 20:25:06 24 4
gpt4 key购买 nike

我在 sql 中使用以下函数创建了哈希值

SQL查询

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

现在我需要获取等效的 C# 函数以获取哈希值并将其传递给存储过程。

我正在使用下面的代码来获得 C# 等效项。但是值不匹配

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:

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

HashValue : 0x104E09499B76CB59420AEEEDBBE187F8

在 C# 中,我从数据库字段值中获取值,如下所示

[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 函数我得到如下值

[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() 的格式看起来更像这样:

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

我认为您正在散列两个不同的字符串。为了使哈希匹配,您需要在计算哈希值之前将日期格式化为相同的格式。

此外,在 sql server 上,您似乎在散列类似以下内容:

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[]

您的字符串和字节之间的转换已关闭。

关于c# - 下面的 SQL HashBytes 函数需要 C# 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38746623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com