Excel中的MD5哈希函数?

14

我想将文档中的一些Excel单元格从序列号转换为该序列号的MD5哈希值。 Excel中是否有预编译的公式可以实现此功能,或者我的唯一选择是使用VBA。如果使用VBA,该如何实现呢?


我认为这个问题已经在这里得到了回答:https://dev59.com/53VC5IYBdhLWcg3w-mZO - NinjaCat
您可以尝试使用Google Scripts的Google电子表格。易于使用,具有众多开源项目。 - northtree
3个回答

10

问题中的一些链接(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搜索,然后单击第一个结果。滚动很多以查看已接受的解决方案。

来源:Password hash function for Excel VBA


哇,自从什么时候开始可以免费查看Experts Exchange上的答案了?我记得以前必须要注册,所以我已经好几年没去过那里了。 - casablanca
3
如果你从谷歌搜索结果中进入一个问题的专家交流页面,你将能够看到回答。如果他们不允许你查看,那么他们早就被谷歌封禁了。谷歌政策不允许向Google机器人和普通用户展示不同的内容。@casablanca - HoLyVieR
2
愿上帝保佑 Stack Overflow。 - lewis

1
我在这里找到了最方便的解决方案:https://www.mrexcel.com/board/threads/convert-string-to-md5-hash.973381/。它利用了 .NET API,而不是全部编码在 VB 中,因此应该速度很快。 https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5cryptoserviceprovider?view=net-6.0 添加以下 VBA 代码:
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)

作为旁注,如果您对MD5的工作原理感兴趣,这个纯Excel实现是一个很好的学习工具:https://tzamtzis.gr/2017/web-analytics/excel-function-md5-hashing-without-vba/

0

我看到这个问题很旧了,但我需要类似的东西,所以我想分享一下我是如何解决这个问题的。

创建一个模块并插入以下代码:

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")))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接