适用于 Excel 的 SHA 256 VBA,无需 .netframework

问题描述 投票:0回答:1

我有一台办公室笔记本电脑,不允许安装 3.5 .netframework,因此无法在 VBA 中使用以下函数进行哈希

系统.安全.加密.SHA256托管

想知道是否有替代代码或过程可以在标准 4.8 .net 框架容器中使用 256 哈希?

谢谢

尝试使用下面的代码但没有产生结果

Function StringToSHA256Hex(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.SHA256Managed")

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

StringToSHA256Hex = outstr
Set enc = Nothing
End Function
excel vba sha256 .net-4.8 .net-framework-version
1个回答
0
投票

原因是库已经过时了。此外,您应该只能使用 VBA 和 CNG(下一代加密)API。

例如:

' Return a Base64 encoded hash of a string using the specified hash algorithm.
' By default, hash algorithm SHA256 is used.
'
' Example:
'   Text = "Get your filthy hands off my desert."
'   Value = Hash(Text)
'   Value -> "AIPgWDlQLv7bvLdg7Oa78dyRbC0tStuEXJRk0MMehOc="
'
' Length of the generated Base64 encoded hash string:
'
'   Encoding    Length
'   MD2         24
'   MD4         24
'   MD5         24
'   SHA1        28
'   SHA256      44      ' Default.
'   SHA384      64
'   SHA512      88
'
' 2021-10-24. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function Hash( _
    ByVal Text As String, _
    Optional ByVal BcryptHashAlgorithmId As BcHashAlgorithm = BcHashAlgorithm.bcSha256) _
    As String
    
    Dim HashBase64          As String
    
    If Text = "" Then
        ' No data. Nothing to do.
    Else
        HashBase64 = ByteBase64(HashData((Text), BcryptHashAlgorithmId))
    End If
    
    Hash = HashBase64
    
End Function

取自我在 GitHub 上的存储库:VBA.Cryptography

© www.soinside.com 2019 - 2024. All rights reserved.