Python 3.3 – Unicode-objects must be encoded before hashing

Question:

Possible Duplicate:
Python hashlib problem “TypeError: Unicode-objects must be encoded before hashing”

Here is a code in Python 3 which generates a password with salt:

import hmac
import random
import string
import hashlib


def make_salt():
    salt = ""
    for i in range(5):
        salt = salt + random.choice(string.ascii_letters)
    return salt


def make_pw_hash(pw, salt = None):
    if (salt == None):
        salt = make_salt() #.encode('utf-8') - not working either
    return hashlib.sha256(pw + salt).hexdigest()+","+ salt


pw = make_pw_hash('123')
print(pw)

The error it gives me is:

Traceback (most recent call last):
  File "C:Usersgermantest.py", line 20, in <module>
    pw = make_pw_hash('123')
  File "C:Usersgermantest.py", line 17, in make_pw_hash
    return hashlib.sha256(pw + salt).hexdigest()+","+ salt
TypeError: Unicode-objects must be encoded before hashing

I’m not allowed to change the algorithm of generating a password, so I only want to fix the error using probably the method encode('utf-8') . How can I do it?

Asked By: user266003

||

Answers:

Simply call the method you already mentioned on the pw and salt strings:

pw_bytes = pw.encode('utf-8')
salt_bytes = salt.encode('utf-8')
return hashlib.sha256(pw_bytes + salt_bytes).hexdigest() + "," + salt
Answered By: ThiefMaster
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.