Password Protection Python
import getpass
import pickle
import hashlib
from os import path
def Encryption(data):
return hashlib.sha512(data).hexdigest()
## First we check if the database exists.
if path.isfile('database.db'):
with open('database.db', 'rb') as fh:
db = pickle.load(fh)
## If it doesn't, we will create one.
else:
## First we create the desired variable.
db = {'torxed' : Encryption('wham'), 'someoneelse' : Encryption('pass')}
## Then we open a filehandle to it.
with open('database.db', 'wb') as fh:
## And then we dump the variable into the filehandle.
## This will keep the variable intact between sessions,
## meaning the next time you start your script, the variable will look the same.
pickle.dump(db, fh)
## Then we ask the user for his/hers credentials.
user = raw_input('Username: ')
_pass = getpass.getpass('Password: ')
## If the user exists in the "db" and the decoded password
## Matches the logged in user, it's a-ok :)
if user in db and db[user] == Encryption(_pass):
print('You logged in')
Adding more users
import pickle, hashlib
def Encryption(data):
return hashlib.sha512(data).hexdigest()
with open('database.db', 'rb') as fh:
db = pickle.load(fh)
db['new_user'] = Encryption('password')
with open('database.db', 'wb') as fh:
pickle.dump(db, fh)
Another way would be to use sys.argv
to get the username and password from the commandline when addings users, in that case:
import pickle, hashlib, sys
if len(sys.argv) < 3:
raise ValueError('Need two parameters, username and password')
def Encryption(data):
return hashlib.sha512(data).hexdigest()
with open('database.db', 'rb') as fh:
db = pickle.load(fh)
db[sys.argv[1]] = Encryption(sys.argv[2])
with open('database.db', 'wb') as fh:
pickle.dump(db, fh)
I should expand on this answer and explain that you should salt passwords as well, and not just store them with a SHA hash.
Also note that passwords are strictly speaking "unsafe" when stored in memory, as there is no SecureString (more) in Python as of writing this. But for basic purposes this answer still applies.