【问题标题】:SHA256 hashing a value in Python and VB.NET produce different hashesSHA256 散列 Python 和 VB.NET 中的值会产生不同的散列
【发布时间】:2018-03-09 15:09:49
【问题描述】:

我正在尝试在 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

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

谁能说出为什么这些函数返回不同的哈希值?

【问题讨论】:

  • 查看字节数。可能只是编码不同
  • 可能从散列一个空字符串(需要更改您的 VB.NET 代码)或单个字节开始以缩小问题范围。

标签: python vb.net hash sha256 hashlib


【解决方案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,或许我们可以为您提供更多帮助。

【讨论】:

    猜你喜欢
    • 2014-01-26
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2015-09-27
    • 2015-01-23
    • 1970-01-01
    相关资源
    最近更新 更多