2017-03-01 58 views
3

我正在使用以下VBA函數來獲取文件的SHA256值;system.security.cryptography.SHA256在.NET 4.5(Windows 10)中管理

Public Function FileToSHA256(sfilename As String) As String 
    Dim enc 
    Dim bytes 
    Dim outstr As String 
    Dim pos As Integer 
    Set enc = CreateObject("System.Security.Cryptography.SHA256Managed") 
    'Convert the string to a byte array and hash it 
    bytes = GetFileBytes(sfilename) 
    bytes = enc.ComputeHash_2((bytes)) 
    'Convert the byte array to a hex string 
    For pos = 1 To LenB(bytes) 
     outstr = outstr & LCase(Right("0" & Hex(AscB(MidB(bytes, pos, 1))), 2)) 
    Next 
    FileToSHA256 = outstr 'Returns a 40 byte/character hex string 
    Set enc = Nothing 
End Function 

Private Function GetFileBytes(ByVal path As String) As Byte() 
    Dim lngFileNum As Long 
    Dim bytRtnVal() As Byte 
    lngFileNum = FreeFile 
    If LenB(Dir(path)) Then ''// Does file exist? 
     Open path For Binary Access Read As lngFileNum 
     ReDim bytRtnVal(LOF(lngFileNum) - 1&) As Byte 
     Get lngFileNum, , bytRtnVal 
     Close lngFileNum 
    Else 
     Err.Raise 53 
    End If 
    GetFileBytes = bytRtnVal 
    Erase bytRtnVal 
End Function 

這完全適用於2013年的Word在Windows 7環境下,我不知道(假設3.5)的.NET版本上運行。

它現在已經啓動到Windows 10環境中(仍然是Word 2013)。我們的IT部門告訴我這是在.NET 4.5上,但根據VBA,它從.NET框架4.0.30319運行。

現在拋出錯誤 - 在這條線

運行時錯誤 '-2146232576(80131700)' 自動化錯誤

;

Set enc = CreateObject("System.Security.Cryptography.SHA256Managed") 

我在項目中引用了MSCORLIB.DLL。

我不明白,如果我需要添加額外的引用或更改代碼。

如果代碼更改是必要的,它也需要覆蓋.NET的早期版本,一些情況檢查涵蓋不同的版本,但我不知道如何執行此操作。

+0

瞎猜,但你嘗試添加從'C的mscorlib程序:\ WINDOWS \ Microsoft.NET \ Framework64 \ v4.0.30319'? –

+0

恐怕沒有用。這可能是因爲它在一個企業環境中,所以我對我有什麼訪問權限有點鎖定。我設法通過繞過mscorlib來整理這個問題。 –

回答