2014-07-01 4 views
0

암호를 해시하려고하는데 성공하지 못했습니다. 이것은 코드입니다.Hashlib unicode error

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) 

이 오류가 발생합니다.

TypeError: Unicode-objects must be encoded before hashing 

내가 뭘 잘못하고 있니?

답변

1

파이썬 2의 경우, 이해가되지 않습니다

if isinstance(string, unicode): 

대신 isinstance(string, (str, str)):, 또한

if isinstance(string, str): 

의 시도. 아마 파이썬 3의 isinstance(string, (str, unicode)):

편집 할 경우, 당신은 sha_constructor()에 인수를 인코딩해야 : 당신이 + 연산자를 사용하는 경우

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

등, 파이썬은 다시 (유니 코드) 문자열을 만들 것이다 당신은 인코딩해야합니다.

+0

파이썬 3은 유니 코드를 지원하지 않습니다. 파이썬 3.4를 사용하고 있습니다 – ajkumar25

+0

올바른 태그를 사용하십시오. 내 대답을 업데이트했습니다. –