ajknzhol
ajknzhol

Reputation: 6460

Hashlib unicode error

I am trying to hash the password and not able to succeed. this is the code.

from hashlib import sha1 as sha_constructor
import random


def generate_sha1(string, salt=None):
    if not isinstance(string, (str, str)):
        string = str(string)
    if isinstance(string, str):
        string = string.encode("utf-8")
    if not salt:
        salt = sha_constructor(str(random.random())).hexdigest()[:5]
    hash = sha_constructor(salt + string).hexdigest()

    return salt, hash


a = generate_sha1('12345')
print(a)

I am getting this error.

TypeError: Unicode-objects must be encoded before hashing

What i am doing wrong?

Upvotes: 0

Views: 444

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328770

For Python 2, try

if isinstance(string, unicode):

instead of

if isinstance(string, str):

Also, isinstance(string, (str, str)): doesn't make sense. Should probably be isinstance(string, (str, unicode)):

EDIT For Python 3, you need to encode the arguments to sha_constructor():

arg = str(random.random()).encode('utf-8')
salt = sha_constructor(arg).hexdigest()[:5]

etc. If you use the + operator, Python will again create a (unicode) string which you have to encode.

Upvotes: 1

Related Questions