SHA256 hash generation of compressed.zip files

Asked

Viewed 372 times

0

I would like to generate a hash with SHA256 of a set of files. For this I compressed all in format .zip and I am using the following code(Python):

from hashlib import sha256

myFile = 'path/to/my/file.zip'

with open(myFile,'rb') as f:
    for line in f:
        hashedWord = sha256(line.rstrip()).hexdigest()

        print(hashedWord)

I was wondering if this code is encoding all the lines of all my files on .zip or if the method is incorrect

  • You want to generate the hash separately for each file?

  • Hi @Andersoncarloswoss, want a unique hash for all files contained in zip

  • 1

    Then you could explain why you went through the file lines?

  • @Andersoncarloswoss using only hashedWord = sha256(f). hexdigest() the code returns error(Typeerror: Object supporting the buffer API require). So I went through all the lines as I figured that if the zip file is a set of lines that will represent the content, the method of going through the lines would also be correct. That is the doubt

1 answer

1


If the intention is to generate the hash from the entire file, just read its contents:

with open(filepath, 'rb') as stream:
    hash = hashlib.sha256(stream.read())

print(hash.hexdigest())

Like commented below by jsbueno, when you iterate over an open file as binary you will not iterate the lines of the file, but rather byte by byte, which would generate a overhead unnecessary for the application.

  • 2

    if the file is opened as binary and not as text (required for a zip file, and more necessary even when the intention is to generate a hash), iterate the contents of the file brings each byte at once, and not every "line" (what would be "line" in zip file, alias??). Using a file in binary mode in a "for" as in the issue code brings a considerable overhead.

  • @jsbueno It makes sense, I didn’t stop to analyze it. Thank you

  • @jsbueno Do you remember if there are any duplicates on this? I looked at it but couldn’t find.

  • I don’t remember seeing questions here about hash generation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.