2

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?

2
  • 1
    Look at the bytes. It could be just the encoding is different Commented Sep 28, 2017 at 1:36
  • 1
    Maybe start with hashing an empty string (needs a change in your VB.NET code) or a single byte to narrow down the problem. Commented Sep 28, 2017 at 1:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.