How to use sha256 hash in Python

The error message means exactly what it says: You have a Unicode string. You can't SHA-256-hash a Unicode string, you can only hash bytes.

But why do you have a Unicode string? Because you're opening a file in text mode, which means you're implicitly asking Python to decode the bytes in that file (using your default encoding) to Unicode. If you want to get the raw bytes, you have to use binary mode.

In other words, just change this line:

with open('words','r') as f:

… to:

with open('words', 'rb') as f:

You may notice that, once you fix this, the print line raises an exception. Why? because you're trying to add a bytes to a str. You're also missing a space, and you're printing the un-stripped line. You could fix all of those by using two arguments to print (as in print(line.rstrip(), "is one of the words")).

But then you'll get output like b'\xc3\x85rhus' is one of the words when you wanted it to print out Århus is one of the words. That's because you now have bytes, not strings. Since Python is no longer decoding for you, you'll need to do that manually. To use the same default encoding that sometimes works when you don't specify an encoding to open, just call decode without an argument. So:

print(line.rstrip().decode(), "is one of the words")

If you want read information as unicode string from the file, this code line would work:
hashedWord = sha256(line.encode('utf-8')).hexdigest()

Tags:

Python

Sha256