How to get hashlib to work on both Python2 and Python3

48 views Asked by At

This code works fine when using Python2, however when using Python3 it gives me this error:

Checksum error: bob.tgz, Unicode-objects must be encoded before hashing

I then made some changes to use byte like objects in the sha256 object but then I started getting:

Checksum error: bob.tgz, 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

So my question is how do I get this code to work on both Python2 and Python3?

import hashlib

filepath = "bob.tgz"
filepath_hashed = "bob.tgz.hashed"
thekey = "asdf1234"
try:
    m = hashlib.sha256()

    file_contents = None
    with open(filepath, "r") as f_in:
        file_contents = f_in.read()
        m.update(file_contents)
    m.update(thekey)
    with open(filepath_hashed, "w") as f_out:
        f_out.write(file_contents)
        f_out.write("~~CHECKSUM~~%s" % m.hexdigest())
except Exception as e:
    print("Checksum error: %s, %s" % (filepath, e))
0

There are 0 answers