我想将文档中的一些Excel单元格从序列号转换为该序列号的MD5哈希值。 Excel中是否有预编译的公式可以实现此功能,或者我的唯一选择是使用VBA。如果使用VBA,该如何实现呢?
问题中的一些链接(Password hash function for Excel VBA)已经失效。以下是该问题上被接受答案的更新版本:
您可以在此处找到VB和VBScript的实现:
http://web.archive.org/web/20080526064101/http://www.frez.co.uk/freecode.htm#md5我相信将其移植到Excel会很容易。
但是有人已经做到了。不幸的是,解决方案位于experts-exchange上,而该网站不允许直接连接。因此,我们必须通过Google。点击这里进行Google搜索,然后单击第一个结果。滚动很多以查看已接受的解决方案。
Function StringToMD5Hex(ByVal s As String) As String
Dim enc As Object
Dim bytes() As Byte
Dim pos As Long
Dim outstr As String
Set enc = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
bytes = StrConv(s, vbFromUnicode)
bytes = enc.ComputeHash_2(bytes)
For pos = LBound(bytes) To UBound(bytes)
outstr = outstr & LCase(Right("0" & Hex(bytes(pos)), 2))
Next pos
StringToMD5Hex = outstr
Set enc = Nothing
End Function
然后使用以下方式调用:
=StringToMD5Hex("string to hash")
=StringToMD5Hex(A2)
我看到这个问题很旧了,但我需要类似的东西,所以我想分享一下我是如何解决这个问题的。
创建一个模块并插入以下代码:
Function stringToUTFBytes(aString)
Dim UTF8
Set UTF8 = CreateObject("System.Text.UTF8Encoding")
stringToUTFBytes = UTF8.GetBytes_4(aString)
End Function
Function md5hashBytes(aBytes)
Dim MD5
Set MD5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
md5hashBytes = MD5.ComputeHash_2((aBytes))
End Function
Function bytesToHex(aBytes)
Dim hexStr, x
For x = 1 To LenB(aBytes)
hexStr = Hex(AscB(MidB((aBytes), x, 1)))
If Len(hexStr) = 1 Then hexStr = "0" & hexStr
bytesToHex = bytesToHex & hexStr
Next
End Function
要调用MD5,您可以使用以下代码:
bytesToHex(md5hashBytes(stringToUTFBytes("change here")))