【问题标题】:Convert string to base 64 from sha1 Hash in Python, returning result as per VBA example在 Python 中将字符串从 sha1 Hash 转换为 base 64,根据 VBA 示例返回结果
【发布时间】:2020-12-16 08:38:40
【问题描述】:

在 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

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 结果:

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

Python 结果:

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

【问题讨论】:

  • 您在 VBA 中使用 utf-8,在 Python 中使用 utf-16。这将给出不同的哈希结果,因为字节模式不同。对两者使用相同的编码。
  • @rossum - 将编码更改为hashlib.sha1(word.encode('utf-8')).digest(),得到b'hvfkN/qlp/zhXR3cuerq6jd2Z7g='。也更新了问题。

标签: python vba algorithm hash cryptography


【解决方案1】:

在 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=

【讨论】:

  • 谢谢,我正是在寻找这个“魔法”。把.decode("utf-8") 删除b-s。
猜你喜欢
  • 1970-01-01
  • 2015-08-09
  • 2018-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多