我目前有一个遗留数据库(SQL 2005),用于生成令牌的哈希字符串。它确实是这样的...SQL 2005 MD5哈希和C#MD5哈希
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”
他们显然是不同的。
那么,是否有可能一致地进行比赛?
因此,如果我得到12345(作为int)和“12345”作为字符串的字节数组,我得到了不同的散列值。另外,如果我创建一个长度为30的空白字节[像我的SQL在其投影中那样),我也会得到不同的结果。那么......是否有一致的方法来做到这一点? – ctorx 2009-09-20 18:08:16