Andomonir Andomonir - 3 years ago 182
Vb.net 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")
Next
Return result


which returns
61ba4908431dfec539e7619d472d7910aaac83c3882a54892898cbec2bbdfa8c

My Python reimplementation:

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


which returns
e33110e0f494d2cf47700bd204e18f65a48817b9c40113771bf85cc69d04b2d8

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]
print()
m.update(binSrc)
print(m.hexdigest()) 

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