Andomonir Andomonir - 3 years ago 182 Question

SHA256 hashing a value in Python and VB.NET produce different hashes

I am trying to re implement a hashing function in Python that had previously been written in VB.NET. The function takes a string and returns the hash. The hash is then stored in a database.

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")
Return result

which returns

My Python reimplementation:

def computehash(source):
if source == "":
return ""
m = hashlib.sha256()
return m.hexdigest()

which returns

The same ten character string is used as the input for both functions.

Can anyone tell why the functions return different hashes?

Answer Source

I used Microsoft's example to create a Visual Basic .Net implementation on TIO. It is functionally equivalent to your implementation and I verified your string builder produces the same output as I'm unfamiliar with VB.

A similar python 3 implementation on TIO produces the same hash as the VB example above.

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

So I can't reproduce your problem. Perhaps if you created a Minimal, Complete and verifiable example we might be able to assist you more.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download