1
import pickle
import hashlib
import uuid

def ask_pass():
   username = input("Please create your username: ")
   password = input("Please create your password: ")

   salt = uuid.uuid4().hex
   hash_code = hashlib.sha256(salt.encode() + password.encode())

   dict = {username: {'SALT': salt,
                      'HASH': hash_code.hexdigest()
                      }
           }

    input_user=open("file.txt", "wb")
    pickle.dump(dict, input_user)

I want to add multiple user to the file.txt but my code delete the previous username and password in stored file.txt every time when i create new username and password. what needs to be change in order to have every user information store it in the file.txt, also how existing users can change their password that being created before?

1 Answers1

0

You are overriding the file each time you save it, losing the previous information.

You need to check it exists and, if that's the case, open it, read it and add the new key to it and, if it doesn't exist, create a new one. Check the code below.

Besides, you should be cautious using open (you can use with or close, as stated here).

import os
import pickle
import hashlib
import uuid

def ask_pass():

    if os.path.isfile("file.txt"):
        with open("file.txt", "rb") as fp:
            dict = pickle.load(fp)
    else:
        dict = {}
    username = input("Please create your username: ")
    password = input("Please create your password: ")

    salt = uuid.uuid4().hex
    hash_code = hashlib.sha256(salt.encode() + password.encode())

    dict[username] ={'SALT': salt,
                     'HASH': hash_code.hexdigest()
                     }

    with open("file.txt", "wb") as fp:
        pickle.dump(dict, fp)
dataista
  • 3,187
  • 1
  • 16
  • 23
  • Note I did an important fix from my first answer which was buggy. Also, a side note: `dict` is a python keyword (the constructor of dictionary) and should not be used for variable names. I didn't change that in the answer itself because it's not the focus of attention, but don't use `dict` as a variable name. – dataista Nov 23 '18 at 02:39
  • Thank you for your suggestion, i want to make the code the way that users be able to change their password? how should i implement it? –  Nov 23 '18 at 03:52
  • Actually, the code the way it is will override the password if you insert a user that already exists. You can check if the user is in dict with `username in dict` and do some special logic in that case (print "Password updated", for example). – dataista Nov 23 '18 at 04:39