0

I have been working on a program that allows you to enter any text you want and it will return the hashed result in sha256. However i am receiving an error on line 4 The whole error message:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    hash_object = hashlib.sha256(password_sign_up)
TypeError: Unicode-objects must be encoded before hashing

The code:

import hashlib
password_sign_up = input("Enter your desired password: ")

hash_object = hashlib.sha256(password_sign_up)
hex_dig = hash_object.hexdigest()
print(hex_dig)
  • 1
    Possible duplicate of [How to correct TypeError: Unicode-objects must be encoded before hashing?](https://stackoverflow.com/questions/7585307/how-to-correct-typeerror-unicode-objects-must-be-encoded-before-hashing) – manveti Feb 02 '19 at 02:01

2 Answers2

0

You're taking the result of the input() function (which returns a str object) and putting it directly into sha256(). The sha256() function requires its parameter to be a bytes object.

You can convert a string to a bytes with:

myNewBytesObject = password_sign_up.encode('utf-8')
kuhnertdm
  • 146
  • 5
  • 1
    While UTF-8 is a very good (and the only sensible) default, remember that Python makes you take this step for a reason—to make you **remember** that characters are not bytes and that there are other encodings (like UTF-16LE for Windows). – Davis Herring Feb 02 '19 at 02:02
0

You have to use .encode('utf-8') for your password. In python 2x, the default encoding for any string is unicode. But in 3x, you will have to encode it to your choice of encoding. e.g. utf-32, utf-8 etc.

Try this: hash_object = hashlib.sha256(password_sign_up.encode('utf-8'))

Sanand Sule
  • 123
  • 5