SHA256在Python中散列值,VB.NET产生不同的散列

时间:2017-09-28 01:27:30

标签: python vb.net hash sha256 hashlib

我正在尝试在Python中重新实现以前用VB.NET编写的散列函数。该函数接受一个字符串并返回哈希值。然后将散列存储在数据库中。

Public Function computeHash(ByVal source As String)
            If source = "" Then
                    Return ""
            End If
            Dim sourceBytes = ASCIIEncoding.ASCII.GetBytes(source)
            Dim SHA256Obj As New Security.Cryptography.SHA256CryptoServiceProvider
            Dim byteHash = SHA256Obj.ComputeHash(sourceBytes)
            Dim result As String = ""
            For Each b As Byte In byteHash
                    result += b.ToString("x2")
            Next
            Return result

返回     61ba4908431dfec539e7619d472d7910aaac83c3882a54892898cbec2bbdfa8c

我的Python重新实现:

def computehash(source):
    if source == "":
        return ""
    m = hashlib.sha256()
    m.update(str(source).encode('ascii'))
    return m.hexdigest()

返回     e33110e0f494d2cf47700bd204e18f65a48817b9c40113771bf85cc69d04b2d8

相同的十个字符串用作两个函数的输入。

有谁可以告诉为什么函数会返回不同的哈希值?

1 个答案:

答案 0 :(得分:1)

我使用Microsoft's exampleTIO上创建了一个Visual Basic .Net实现。它在功能上等同于你的实现,我验证你的字符串构建器产生的输出与我不熟悉的VB相同。

TIO上类似的python 3实现产生与上面VB示例相同的哈希值。

import hashlib
m = hashlib.sha256()
binSrc = "abcdefghij".encode('ascii')
# to verify the bytes
[print("{:2X}".format(c), end="") for c in binSrc]
print()
m.update(binSrc)
print(m.hexdigest()) 

所以我无法重现你的问题。也许如果您创建了Minimal, Complete and verifiable example,我们可以为您提供更多帮助。