Skip to main content
 首页 » 编程设计

c#之SQL 2005 MD5 哈希和 C# MD5 哈希

2024年02月24日18arxive

我目前有一个遗留数据库 (SQL 2005),它为 token 生成哈希字符串。它是这样的...

DECLARE @RowID INT 
DECLARE @hashString VARCHAR(128) 
 
SET @RowID = 12345 
SET @salt= 0xD2779428A5328AF9 
 
SET @hashBinary = HASHBYTES(('MD5', @salt + CAST(@RowID AS VARBINARY(30))) 
SET @hashString = sys.fn_varbintohexstr(@hashBinary) 

如果我执行此操作,我的哈希字符串将如下所示:“0x69a947fd71b853485007f0d0be0763a5”

现在,我需要在 C# 中复制相同的逻辑,这样我就可以删除生成这些哈希值的数据库依赖性,而且它必须向后兼容。

我在 C# 中实现如下:

byte[] saltBytes = BitConverter.GetBytes(0xD2779428A5328AF9); 
byte[] pidBytes = BitConverter.GetBytes(12345); 
 
byte[] bytesToHash = new byte[saltBytes.Length + pidBytes.Length]; 
 
for (int i = 0; i < saltBytes.Length; i++) 
{ 
    bytesToHash[i] = saltBytes[i]; 
} 
 
for (int i = 0; i < pidBytes.Length; i++) 
{ 
    bytesToHash[saltBytes.Length + 1] = pidBytes[i]; 
} 
 
MD5CryptoServiceProvider hasher = new MD5CryptoServiceProvider(); 
byte[] hashedBytes = hasher.ComputeHash(bytesToHash); 
 
string hashString = BitConverter.ToString(hashedBytes).ToLower().Replace("-", ""); 

问题是,我的 C# 实现生成了这个散列:“715f5d6341722115a1bfb2c82e4421bf”

它们明显不同。

那么,是否有可能使匹配始终如一?

请您参考如下方法:

在我看来,您的第二个循环中存在错误。尝试将“+ 1”更改为“+ i”...

for (int i = 0; i < pidBytes.Length; i++) 
{ 
    // the line below just overwrites the same position multiple times 
    // bytesToHash[saltBytes.Length + 1] = pidBytes[i]; 
    bytesToHash[saltBytes.Length + i] = pidBytes[i]; 
} 

在您的示例中,您只是多次覆盖数组中的相同位置,而不是从该点向前设置每个项目。