Let's Study/Python programming

TypeError: Unicode-objects must be encoded before hashing

샤에테 2020. 9. 12. 13:19

python3에서 import hashlib의 hashlib.sha256 함수를 이용하는 중에

 

"TypeError: Unicode-objects must be encoded before hashing "

 

이런 에러가 뜨는 경우가 있는데, 이는 hashlib 사용 시 byte 형태가 필요해서 에러가 생긴다.

python3의 문자열은 기본적으로 unicode이며, 문제 해결을 위해 encode('utf-8')을 붙여주면 된다.

 

예시코드:

  string = "test"

  hashlib.sha256(string.encode('utf-8')).hexdigest()