2019-01-31

VBA - SHA256 해쉬 문자열 만들기

참조 링크:
https://en.m.wikibooks.org/wiki/Visual_Basic_for_Applications/String_Hashing_in_VBA


도구 추가:
Mscorlib 4.0 64bit

소스:
Function SHA256(sIn As String, Optional bB64 As Boolean = 0) As String
    'prerequisite
    'Set a reference to mscorlib 4.0 64-bit
    Dim oT As Object, oSHA256 As Object
    Dim TextToHash() As Byte, bytes() As Byte
    Set oT = CreateObject("System.Text.UTF8Encoding")
    Set oSHA256 = CreateObject("System.Security.Cryptography.SHA256Managed")
    TextToHash = oT.GetBytes_4(sIn)
    bytes = oSHA256.ComputeHash_2((TextToHash))
    If bB64 = True Then
       SHA256 = ConvToBase64String(bytes)
    Else
       SHA256 = ConvToHexString(bytes)
    End If
    Set oT = Nothing
    Set oSHA256 = Nothing
End Function
Function ConvToHexString(vIn As Variant) As Variant
    Dim oD As Object
    Set oD = CreateObject("MSXML2.DOMDocument")
      With oD
        .LoadXML ""
        .DocumentElement.DataType = "bin.Hex"
        .DocumentElement.nodeTypedValue = vIn
      End With
    ConvToHexString = Replace(oD.DocumentElement.Text, vbLf, "")
    Set oD = Nothing
End Function
결과:
Base64: MDkBFbBmlo/AYoaEwOl7KAUEnj5dfJ/+1pxVFjKkkuc=
44 characters in length
Hex: 30390115b066968fc0628684c0e97b2805049e3e5d7c9ffed69c551632a492e7
64 characters in length






 


No comments:

Post a Comment