简体   繁体   中英

Convert string to base 64 from sha1 Hash in Python, returning result as per VBA example

Having a hashing function in VBA, which gets a string and returns a hash, I need to make a function in Python, which returns the same hash.

VBA code:

Public Function Base64Sha1(inputText As String)

    Dim asc As Object
    Dim enc As Object
    Dim textToHash() As Byte
    Dim SharedSecretKey() As Byte
    Dim bytes() As Byte

    Set asc = CreateObject("System.Text.UTF8Encoding")
    Set enc = CreateObject("System.Security.Cryptography.HMACSHA1")

    textToHash = asc.GetBytes_4(inputText)
    SharedSecretKey = asc.GetBytes_4(inputText)
    enc.Key = SharedSecretKey

    bytes = enc.ComputeHash_2((textToHash))
    Base64Sha1 = EncodeBase64(bytes)        

End Function

Private Function EncodeBase64(arrData() As Byte) As String

    Dim objXML As Object
    Dim objNode As Object

    Set objXML = CreateObject("MSXML2.DOMDocument")
    Set objNode = objXML.createElement("b64")

    objNode.DataType = "bin.base64"
    objNode.nodeTypedValue = arrData
    EncodeBase64 = objNode.Text

End Function

Python code :

import hashlib
import base64

def string_to_hash(word):
    digest = hashlib.sha1(word.encode('utf-8')).digest()
    return base64.b64encode(digest)

print(string_to_hash('a'))

VBA results:

debug.print(Base64Sha1("a"))
OQLthH/yiTC18UGr+otHFoElNnM=

Python results:

print(string_to_hash('a'))
b'hvfkN/qlp/zhXR3cuerq6jd2Z7g='

In the VB code, the hash is determined with HMAC /SHA1 and not simply with SHA1. The following Python code provides the same result as the VB code:

import hmac
import hashlib
import base64

def string_to_hash(word):
    word = word.encode('utf-8')
    hash = hmac.new(word, word, hashlib.sha1).digest()
    return base64.b64encode(hash).decode("utf-8")

print(string_to_hash('a')) # OQLthH/yiTC18UGr+otHFoElNnM=

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM