Python MD5 comparison in Python 3.2

I am trying to check two files downloaded from a server. The first contains data, and the second file contains the MD5 checksum.

I created a function that returns hexdigest from a data file as follows:

def md5(fileName):
    """Compute md5 hash of the specified file"""
    try:
        fileHandle = open(fileName, "rb")
    except IOError:
        print ("Unable to open the file in readmode: [0]", fileName)
        return
    m5Hash = hashlib.md5()
    while True:
        data = fileHandle.read(8192)
        if not data:
            break
        m5Hash.update(data)
    fileHandle.close()
    return m5Hash.hexdigest()

I am comparing files using the following:

file = "/Volumes/Mac/dataFile.tbz"
fileHash = md5(file)

hashFile = "/Volumes/Mac/hashFile.tbz.md5"
fileHandle = open(hashFile, "rb")
fileHandleData = fileHandle.read()

if fileHash == fileHandleData:
    print ("Good")
else:
    print ("Bad")

The file comparison failed, so I printed both fileHash, and fileHandleData, and we get the following:

[0] b'MD5 (hashFile.tbz) = b60d684ab4a2570253961c2c2ad7b14c\n'
[0] b60d684ab4a2570253961c2c2ad7b14c

From the above, the hash values ​​are identical. Why does hash comparison fail? I am new to python and am using python 3.2. Any suggestions?

Thank.

+3
source share
4 answers

Comparison is not suitable for the same reason as false:

a = "data"
b = b"blah (blah) - data"
print(a == b)

The format of this .md5 file is strange, but if it is always in that format, an easy way to check is:

if fileHandleData.rstrip().endswith(fileHash.encode()):

Hash (Unicode), . , .

, - , , .

, , :

if fileHash.encode() in fileHandleData:
+1

- fileHandle. MD5 (hashFile.tbz) =, , :

if fileHash == fileHandleData.rsplit(' ', 1)[-1].rstrip():
    print ("Good")
else:
    print ("Bad")

, Python 3, rsplit() rstrip() API- . , , / HandleData/fileHash ( (Unicode), ).

+1

The hash values ​​are identical, but there are no lines. You need to get the hex value of the digest, and you need to parse the hash from the file. Once you have done this, you can compare them for equality.

0
source

Try the "Hash.strip file (" \ n ") ... then compare two. This should fix the problem.

0
source

All Articles