我参考网站上的示例代码,使用.net Framework“System.Security.Cryptography.SHA1CryptoServiceProvider”制作了一个VBA代码。这段代码是正确的。例如
Function SHA1Hash(str As String) As String
Dim sha1 As Object
Dim bytes() As Byte
Dim hash() As Byte
Dim i As Integer
Set sha1 = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider")
bytes = StrConv(str, vbFromUnicode)
hash = sha1.ComputeHash_2((bytes))
SHA1Hash = ""
For i = 0 To UBound(hash)
SHA1Hash = SHA1Hash & Right("00" & Hex(hash(i)), 2)
Next i
End Function
Sub SHA1Hash_Main()
Debug.Print SHA1Hash("hello world")
End Sub
但是我不明白为什么 ComputeHash 必须在 VBA 中称为 ComputeHash_2。
所以我查了这个文件
官方文档中有3个ComputeHash方法,示例代码中调用的ComputeHash(Byte[]),按照在文档中出现的先后顺序排在最前面
1. ComputeHash(Byte[])
2. ComputeHash(Byte[], Int32, Int32)
3. ComputeHash(Stream)
因此,如果在 VBA 中您必须使用“_x”来指定相同的定义方法,那么如果您信任文档顺序,为什么不用“_1”呢?
然而,下面ComputeHash_1的代码给出了这样的错误。 “对象不支持此属性或方法(错误 438)。”
Function SHA1Hash(str As String) As String
Dim sha1 As Object
Dim bytes() As Byte
Dim hash() As Byte
Dim i As Integer
Set sha1 = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider")
bytes = StrConv(str, vbFromUnicode)
hash = sha1.ComputeHash_1((bytes))
SHA1Hash = ""
For i = 0 To UBound(hash)
SHA1Hash = SHA1Hash & Right("00" & Hex(hash(i)), 2)
Next i
End Function
Sub SHA1Hash_Main()
Debug.Print SHA1Hash("hello world")
End Sub
为什么是“ComputeHash_2”?在 VBA 中使用时是否有任何文档或规范支持“_2”?