Taylor Stevens
Taylor Stevens

Reputation: 95

Storing username and password into a dictionary?

Currently at the moment im working a small login screen in python, What i want it to do is ask a user to register if theyre isnt a account already created, But one small problem im having is how can i save the username and password into a dictionary, I would also like to know how i would save the dictionary to a .txt file that can be loaded to restore user info/variables if this is possible.

Im not too sure whether im meant to ask for help with my code or im allowed to ask questions like this, I just need a reffernce or a little help. Also just to add im not asking for someone to do it for me, Just to give me a shove in the right direction

Please dont flame me ;p

import sys
import math
user = None
password = None
store = dict()
newUser = True


while newUser == True:
    userguess=""
    passwordguess=""
    print("Hello, Please create a unique username and password.")
    user = input("USERNAME: ")
    password = input("PASSWORD: ")
    store[user] = password
    print(store)

That is what i have tried so far, I gathered the storing to dictionary from another page on here, Was just looking for a breakdown on assigning stuff to a key

Upvotes: 2

Views: 4309

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 114038

you dont ... you save a hash into a dictionary (a hash is simpley a non reversable encoding)

eg: md5("password") == '5f4dcc3b5aa765d61d8327deb882cf99'

however there is no real way to go from that back to the password

nothing_does_this('5f4dcc3b5aa765d61d8327deb882cf99') == "password"

(not entirely true... but close enough fo the concept)

import hashlib
def create_users()
   users = {}
   while True:
      username = raw_input("Enter Username:")
      password = raw_input("Enter Password:")
      users[username] = hashlib.md5(password).hexdigest()
      if raw_input("continue?")[0].lower() != "y":
          return users

def login(userdict):
    username = raw_input("Username:")
    password = raw_input("Password:")
    return userdict.get(username,None) == hashlib.md5(password).hexdigest()

users = create_users()
if login(users):
   print "Double Winning!!!"
else:
   print "You Lose Sucka!!!"

as pointed out md5 is not a very secure hash, there are much better ones to use sha256 is pretty good still I think, bcrypt is even better (for some definition of better) ... however md5 is a simple hash to help with understanding what they are..

Upvotes: 4

Frank Riccobono
Frank Riccobono

Reputation: 1063

If you already have constructed this dictionary, you can save it to a file with pickle.

pickle.dump( user_dict, open( "save.p", "wb" ) )

However, you should be aware of best practices when storing passwords and make sure you are storing a securely hashed version of the password rather than its value in plaintext.

Upvotes: 3

Related Questions