Cryces
Cryces

Reputation: 37

How to convert a password into a hash value?

I am trying to create a login system for my project and I need to use hashing for the users password, I am unsure how to hash a variable name and convert it into bytes to give a hex result for the password.

tried using:

hash_object = hashlib.md5(b(password))

and:

hash_object = hashlib.md5((password))

Code:

import hashlib

user = {}

username = input("What is your username? ")
password = input("What is your password? ")

hash_object = hashlib.md5((password))
print(hash_object.hexdigest())

Error:

Traceback (most recent call last):
  File "E:\loginsystem.py", line 8, in <module>
    hash_object = hashlib.md5((password))
TypeError: Unicode-objects must be encoded before hashing

Upvotes: 3

Views: 1022

Answers (1)

Joe Iddon
Joe Iddon

Reputation: 20434

Encode the password string with the .encode method.

import hashlib

user = {}

username = input("What is your username? ")
password = input("What is your password? ")

hash_object = hashlib.md5(passsword.encode('utf8'))
print(hash_object.hexdigest())

I recommend this great thread that might clear some things up:

What is the difference between a string and a byte string?

Upvotes: 1

Related Questions