问题描述
我有一个 SQL 表,我在其中存储必须唯一的大字符串值.为了确保唯一性,我在一个列上有一个唯一索引,我在其中存储了大字符串的 MD5 哈希的字符串表示.
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.
保存这些记录的 C# 应用程序使用以下方法进行散列:
The C# app that saves these records uses the following method to do the hashing:
为了调用它,我首先使用UTF-8编码将string
转换为byte[]
:
In order to call this, I first convert the string
to byte[]
using the UTF-8 encoding:
现在我希望能够在 SQL 中实现这个散列函数,使用 HASHBYTES
函数,但我得到不同的值:
Now I would like to be able to implement this hashing function in SQL, using the HASHBYTES
function, but I get a different value:
这是因为 SQL 计算字符串的 UTF-16 表示的 MD5.如果我执行 CreateMd5HashString(Encoding.Unicode.GetBytes("abc"))
,我在 C# 中得到相同的结果.
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.
有没有办法让 SQL Server 计算字符串的 UTF-8 字节的 MD5 哈希值?
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.
推荐答案
您需要创建一个 UDF 来将 NVARCHAR 数据转换为 UTF-8 表示形式的字节.假设它被称为 dbo.NCharToUTF8Binary
那么你可以这样做:
You need to create a UDF to convert the NVARCHAR data to bytes in UTF-8 Representation. Say it is called dbo.NCharToUTF8Binary
then you can do:
这是一个可以做到这一点的 UDF:
Here is a UDF which will do that:
这篇关于计算 UTF8 字符串的 MD5 哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!