[英]Convert string to base 64 from sha1 Hash in Python, returning result as per VBA example
在 VBA 中有一個散列函數,它獲取一個字符串並返回一個散列,我需要在 Python 中創建一個函數,它返回相同的散列。
VBA代碼:
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
蟒蛇代碼:
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結果:
debug.print(Base64Sha1("a"))
OQLthH/yiTC18UGr+otHFoElNnM=
蟒蛇結果:
print(string_to_hash('a'))
b'hvfkN/qlp/zhXR3cuerq6jd2Z7g='
在 VB 代碼中,散列是用HMAC /SHA1 確定的,而不是簡單地用 SHA1 確定的。 以下 Python 代碼提供與 VB 代碼相同的結果:
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=
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.