Search code examples
pythonhashlib

Hashing in .iso file in Python from user input; can hash string corresponding with directory, not actual file


I am trying to hash an .iso file from user input. Using the open() function in Python, I can successfully hash the string corresponding to the directory of the .iso file itself, but cannot obtain a correct hash of the .iso file.

My code is as follows:

import hashlib

userInput = input("Path to the file: ")
isoFile = open(userInput, 'rb')
result = hashlib.sha512(userInput.encode())

print("The hash value of the file is: ")
print(result.hexdigest())

I have tried appending the following lines before the print() function:

readIso = isoFile.read()
result.update(readIso)

which generates a different hash, ostensibly corresponding to the actual .iso file in question.

According to sha512sum, the hash of the .iso file should be:

c9b75d55fa501415ad8a1b3e597cb3c398aaf4f8c08e9219b676c07280b1d9d8cd2c6dcc6e97e077acef3d4fac4e15b021df41671b5e8f15bb557050a284e684

When running the script with the aforementioned lines appended, the output becomes:

28cf1c2aabc1758dafb89ed5d3e75117e255bd4101522972e30d7b4f2a4b803a979747db3c655a4f475eef8d2863dd373c5c260881c6fe067d8215641e37bc09

Thanks in advance for any assistance provided.


Solution

  • I solved the problem in question by doing a couple of things:

    I removed userInput.encode from result = hashlib.sha512(userInput.encode())

    And I appended the following loop onto my script following isoFile = open(userInput, 'rb'):

    while True:
        readIso = isoFile.read(1024)
    
        if readIso:
            result.update(readIso)
        else:
            hexHash = result.hexdigest()
            break