I have an SQL table in which I store large string values that must be unique.
In order to ensure the uniqueness, I have a unique index on a column in which I store a string representation of the MD5 hash of the large string.
The C# app that saves these records uses the following method to do the hashing:
public static string CreateMd5HashString(byte[] input)
{
var hashBytes = MD5.Create().ComputeHash(input);
return string.Join("", hashBytes.Select(b => b.ToString("X")));
}
In order to call this, I first convert the string
to byte[]
using the UTF-8 encoding:
// this is what I use in my app
CreateMd5HashString(Encoding.UTF8.GetBytes("abc"))
// result: 90150983CD24FB0D6963F7D28E17F72
Now I would like to be able to implement this hashing function in SQL, using the HASHBYTES
function, but I get a different value:
print hashbytes('md5', N'abc')
-- result: 0xCE1473CF80C6B3FDA8E3DFC006ADC315
This is because SQL computes the MD5 of the UTF-16 representation of the string.
I get the same result in C# if I do CreateMd5HashString(Encoding.Unicode.GetBytes("abc"))
.
I cannot change the way hashing is done in the application.
Is there a way to get SQL Server to compute the MD5 hash of the UTF-8 bytes of the string?
I looked up similar questions, I tried using collations, but had no luck so far.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…