why am I getting cryptography fernet InvalidToken when using the same key - python

Hello so I am making a password manager and I want to encrypt the password file, so I generate and create the first password and when I read it and decrypt it reads it. And then when making another password it creates it but then when decrypting it throws an error. From what I can see I am using the same key.
Here is the code:
#imports
import random,string,os,sys
from cryptography.fernet import Fernet
import bcrypt
if os.path.isfile('salt.txt'):
#Gets the salt
with open('salt.txt','rb') as saltfile:
salt = saltfile.read()
else:
with open('salt.txt','wb')as saltfile:
salt = bcrypt.gensalt()
saltfile.write(salt)
saltfile.close()
#Hashes the item
def hashPass(item):
global passwordOut
hashed = bcrypt.hashpw(item,salt)
passwordOut = hashed
return passwordOut
#Password Generator
def setPassword(length=30,char=string.ascii_letters+string.digits+string.punctuation):
global generatedPassword
generatedPassword= ''.join(random.choice(char) for x in range(length))
return generatedPassword
if os.path.isfile('mykey.key') == True:
#Opens the key
with open('mykey.key', 'rb') as mykey:
print('True')
key = mykey.read()
f = Fernet(key)
mykey.close()
elif os.path.isfile('mykey.key')== False:
print('False')
# Generates a kay
key = Fernet.generate_key()
# Writes a new key
with open('mykey.key', 'wb') as mykey:
mykey.write(key)
f = Fernet(key)
mykey.close()
#Sets the key
#Stating initalization
print("Hello and welcome to your password manager!")
while True:
#If there is a user file
if os.path.isfile('user.txt'):
#Read the user file
with open('user.txt','rb') as user_file:
file = user_file.read()
#Gets the inputs
getUser = input("Enter your username ").encode('utf-8')
getPass = input('Enter your password: ').encode('utf-8')
#Hashes the inputs through the hashing funcion
hashPass(item=getUser)
usr = passwordOut
hashPass(item=getPass)
passw = passwordOut
#If the users hashed input is the same in the users file it carries on with the procedure
if usr in file and passw in file:
while True:
print("""Pick from the list of what you want to do:
1. Generate a new password
2. See passwords
3. Quit""")
usrinput = int(input('Enter a number from the menu: '))
if usrinput == 1:
print("\nGenerating password...")
setPassword()
usrinput = input("What is the password for: ")
splitter = ': '
#
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','ab')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
print("Your new password for: "+usrinput)
print("And the password is: "+generatedPassword)
password_file.close()
else:
with open('passwordenc.txt','wb')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
print("Your new password for: " + usrinput)
print("And the password is: " + generatedPassword)
password_file.close()
if usrinput == 2:
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','rb') as password_file:
read = password_file.read()
decrypt = f.decrypt(read)
print(decrypt)
password_file.close()
else:
print('File not found! Need to create a new file.')
if usrinput == 3:
quit()
#If not the same it loops back around
else:
print("\nUser not found!\n")
#If there is no file:
else:
#Gets a user input
username = input('Enter a username: ').encode('utf-8')
password = input('Enter a password, cannot be changed! ').encode('utf-8')
#Hashes the user input
hashPass(item=username)
usr = passwordOut
hashPass(item=password)
passw = passwordOut
#Writes the user input
with open('user.txt','wb') as user:
user.write(usr)
user.write(passw)
print('\nUser has been created!\n')
Here is the terminal code:
C:\Users\James\Documents\passwords\venv\Scripts\python.exe C:/Users/James/Documents/passwords/main.py
True
Hello and welcome to your password manager!
Enter your username james
Enter your password: Kaits_1204
Pick from the list of what you want to do:
1. Generate a new password
2. See passwords
3. Quit
Enter a number from the menu: 2
Traceback (most recent call last):
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 119, in _verify_signature
h.verify(data[-32:])
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\hazmat\primitives\hmac.py", line 74, in verify
ctx.verify(signature)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\hazmat\backends\openssl\hmac.py", line 75, in verify
raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/James/Documents/passwords/main.py", line 106, in <module>
decrypt = f.decrypt(read)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 80, in decrypt
return self._decrypt_data(data, timestamp, time_info)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 137, in _decrypt_data
self._verify_signature(data)
File "C:\Users\James\Documents\passwords\venv\lib\site-packages\cryptography\fernet.py", line 121, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken
Process finished with exit code 1

The problem is that you take input of user for chosen account password then you append splitter and random generated password then '/n'. After that you encrypt this var using fernet. This method will work to view your first password since with first password you read and decrypt whole file but not with multiple encrypted passwords since each var encryption is unique (having different IV) which means that to decrypt all the passwords you will need a way to signal the end of an encrypted password and beginning of another encrypted password so that you pass to ferent the correct ciphertext with correct margins. This can be done by simply adding --END OF PASSWORD-- after each encryption write to password file. Then during reading of passwords you can just split pass file on these margins and pass result to fernet.
NOTE: dont use this code as your password manager since although you encrypt your passwords you are leaving your master password in mykey.key unencrypted which makes this totally useless.
import random,string,os,sys
from cryptography.fernet import Fernet
import bcrypt
if os.path.isfile('salt.txt'):
#Gets the salt
with open('salt.txt','rb') as saltfile:
salt = saltfile.read()
else:
with open('salt.txt','wb')as saltfile:
salt = bcrypt.gensalt()
saltfile.write(salt)
#saltfile.close() # You dont need to close
#Hashes the item
def hashPass(item):
global passwordOut
hashed = bcrypt.hashpw(item,salt)
passwordOut = hashed
# return passwordOut
# Random Password Generator
def setPassword(length=30,char=string.ascii_letters+string.digits+string.punctuation):
global generatedPassword
generatedPassword= ''.join(random.choice(char) for x in range(length))
return generatedPassword
if os.path.isfile('mykey.key') == True:
#Opens the key
with open('mykey.key', 'rb') as mykey:
print('True')
key = mykey.read()
f = Fernet(key)
elif os.path.isfile('mykey.key')== False:
print('False')
# Generates a kay
key = Fernet.generate_key()
# Writes a new key
with open('mykey.key', 'wb') as mykey:
mykey.write(key)
f = Fernet(key)
#mykey.close() # with doesnt need file to be closed
#Sets the key
#Stating initalization
print("Hello and welcome to your password manager!")
while True:
#If there is a user file
if os.path.isfile('user.txt'):
#Read the user file
with open('user.txt','rb') as user_file:
file = user_file.read()
print("File ", file)
#Gets the inputs
getUser = input("Enter your username ").encode('utf-8')
getPass = input('Enter your password: ').encode('utf-8')
#Hashes the inputs through the hashing funcion
hashPass(item=getUser)
usr = passwordOut
hashPass(item=getPass)
passw = passwordOut
#If the users hashed input is the same in the users file it carries on with the procedure
if usr in file and passw in file:
while True:
print("""Pick from the list of what you want to do:
1. Generate a new password
2. See passwords
3. Quit""")
usrinput = int(input('Enter a number from the menu: '))
if usrinput == 1:
print("\nGenerating password...")
setPassword()
usrinput = input("What is the password for: ")
splitter = ': '
#
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','ab')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
password_file.write(b"--END OF PASSWORD--")
print("Your new password for: "+usrinput)
print("And the password is: "+generatedPassword)
else:
with open('passwordenc.txt','wb')as password_file:
var = usrinput + splitter + generatedPassword + '\n'
encrypted = f.encrypt(bytes(var.encode('utf-8')))
password_file.write(encrypted)
password_file.write(b"--END OF PASSWORD--")
print("Your new password for: " + usrinput)
print("And the password is: " + generatedPassword)
if usrinput == 2:
if os.path.isfile('passwordenc.txt'):
with open('passwordenc.txt','r') as password_file:
whole_file = password_file.read()
password_list = whole_file.split("--END OF PASSWORD--")
for password in password_list:
if password:
decrypt = f.decrypt(bytes(password, encoding="utf-8"))
print("Decrypted pass: ", decrypt)
else:
print('File not found! Need to create a new file.')
if usrinput == 3:
quit()
#If not the same it loops back around
else:
print("\nUser not found!\n")
#If there is no file:
else:
#Gets a user input
username = input('Enter a username: ').encode('utf-8')
password = input('Enter a password, cannot be changed! ').encode('utf-8')
#Hashes the user input
hashPass(item=username)
usr = passwordOut
hashPass(item=password)
passw = passwordOut
#Writes the user input
with open('user.txt','wb') as user:
user.write(usr)
user.write(passw)
print('\nUser has been created!\n')

Related

Checking for the users input in a text file and if it is there it will print something

I am making a login/ sign up page in python for fun but im kinda stuck.
I have made my sign up page but im stuck with the login page
I need some code that reads the text file(info.txt) for what the user inputted and if they are both there in the same line it will print something
https://i.stack.imgur.com/ONsWB.png <- here is what my files look like and here is my sign up code
print("Welcome to sign up Enter your details below")
username = input("Enter Username:")
password = input("Enter Password:")
#input text
input_dictionary = {"one" : 1, "two" : 2}
#open file
file = open("info.txt", "w")
#convert variable to string
str = repr(username)
lol = repr(password)
file.write(str + ":" + lol + "\n")
#close file
file.close()
f = open('info.txt', 'r')
if f.mode=='r':
contents= f.read()
print("Well done you now have a account!")
and so far my login page code is
username = input("Username:")
password = input("Password:")
Something like this should work
username = input("Username:")
password = input("Password:")
with open('info.txt') as f:
# split file on newline
users = f.read().split('\n')
if username + ":" + password in users:
# user logged in
you could do something like this:
import time as t
f_content = open("info.txt",'r').read()
while True:
username = input("Username:")
password = input("Password:")
infos = [username,password]
for user in f_content:
user_info = user.split(":")
if user_info == infos:
found = True
print("Successfully logged in!")
#some code
if not found:
print("User was not found!\nWait 20 seconds to reset")
t.sleep(20)
and you should always put things like this in functions, to avoid calling external modules:
import time as t
f_content = open("info.txt",'r').read()
def signin():
print("Welcome to sign up Enter your details below")
username = input("Enter Username:")
password = input("Enter Password:")
#input text
input_dictionary = {"one" : 1, "two" : 2}
#open file
file = open("info.txt", "w")
#convert variable to string
str = repr(username)
lol = repr(password)
file.write(str + ":" + lol + "\n")
#close file
file.close()
f = open('info.txt', 'r')
if f.mode=='r':
contents= f.read()
print("Well done you now have a account!")
def login(username,password):
infos = [username,password]
for user in f_content:
user_info = user.split(":")
if user_info == infos:
found = True
print("Successfully logged in!")
#some code
if not found:
print("User was not found!\nWait 20 seconds to reset")
t.sleep(20)
if __name__ == '__main__':
if f_content == '':
signin()
exit()
while True:
username = input("Username >> ")
password = input("Password >> ")
login(username,password)
if you though i overcomplicated things, you should do just like this:
username = input("Username:")
password = input("Password:")
f = open('info.txt')
# split file on newline
users = f.read().split('\n')
if username + ":" + password in users:
# do some code
...

How to convert a list to a file and the load that file into a list again?

I am trying to create a lock which can only be opened with a password in python. You can also create an account to login to the lock. How do I save accounts to a list and access them again when I want to login?
This is what I have tried:
from sys import exit
import re
def num_there(s):
return any(i.isdigit() for i in s)
def special_character_check(String):
rex = re.compile('[#_!#$%^&*()<>?/\|}{~:]')
search = rex.search(String)
if search == None:
print('This password has no special characters')
exit()
f = open('file.txt', 'w')
e = open('file2.txt', 'w')
login_signup = input('Do you want to login or sign up?')
available_accounts_usernames = [f]
available_accounts_passwords = [e]
content = available_accounts_usernames
content2 = available_accounts_passwords
login_username = ''
login_password = ''
signup_username = ''
signup_password = ''
signup_confirm_password = ''
if login_signup in ('login', 'Login'):
login_username = input('Please enter your username')
login_password = input('Please enter your password')
if login_username not in (available_accounts_usernames) or login_password not in (available_accounts_passwords):
print('Access denied')
exit()
if login_username in (available_accounts_usernames) and login_password in (available_accounts_passwords):
print('Access granted')
exit()
if login_signup in ('sign up', 'Sign up'):
signup_username = input('Please enter a username. This username will be asked if you want to login')
signup_password = input('Please enter a password. You will be asked to confirm your password')
if len(signup_password) < 8:
print('This password should be more than 8 characters. PLease enter your info again.')
exit()
if num_there(signup_password) == False:
print('This password has no number')
exit()
if num_there(signup_password) == True:
special_character_check(signup_password)
signup_confirm_password = input('Please confirm your password')
if signup_password == signup_confirm_password:
available_accounts_usernames.append(signup_username)
available_accounts_passwords.append(signup_password)
print('Your account has been created. Please login to access it.')
if signup_password != signup_confirm_password:
print("These passwords don't match. Please enter your info again")
exit()
content = available_accounts_usernames
content2 = available_accounts_passwords
f.write(str(content))
e.write(str(content2))
It just doesn't work. Sorry if its a long question. I am new to python
To solve the problem of storing and reading data you can use some data format such as pickle, json, yaml, toml. But for the simplicity and for the most common data format we will use json. Now, json comes with the python standard library by default and here is some sample json files if you want to know how json looks:
{
"name": "xcodz",
"languages": ["python", "html", "css"],
}
[
"eggs",
"bread",
"wheat",
{
"name": "CustomObject",
"cost": 1000
},
"noodles"
]
So how does files work. you can open a file using open method.
file = open('MyFile.txt', 'r') # 'r' can be replaced with different modes
file.read() # read all the contents
file.write('some content') # works only when mode is 'w', 'wb', 'w+b', 'a', 'ab', 'a+b'
file.seek(0) # change the position
now for your purpose here is the json code:
from sys import exit
import re
import json
import os # For creating defaults
def num_there(s):
return any(i.isdigit() for i in s)
def special_character_check(String):
rex = re.compile('[#_!#$%^&*()<>?/\|}{~:]')
search = rex.search(String)
if search == None:
print('This password has no special characters')
exit()
if not os.path.isfile('database.json'):
with open('database.json', 'w') as f:
f.write('{"usernames": [], "passwords": []}')
with open('database.json', 'r') as f:
data = json.load(f)
available_accounts_usernames = data['usernames']
available_accounts_passwords = data['passwords']
login_signup = input('Do you want to login or sign up?')
content = available_accounts_usernames
content2 = available_accounts_passwords
login_username = ''
login_password = ''
signup_username = ''
signup_password = ''
signup_confirm_password = ''
if login_signup in ('login', 'Login'):
login_username = input('Please enter your username')
login_password = input('Please enter your password')
if login_username not in (available_accounts_usernames) or login_password not in (available_accounts_passwords):
print('Access denied')
exit()
if login_username in (available_accounts_usernames) and login_password in (available_accounts_passwords):
print('Access granted')
exit()
if login_signup in ('sign up', 'Sign up'):
signup_username = input('Please enter a username. This username will be asked if you want to login')
signup_password = input('Please enter a password. You will be asked to confirm your password')
if len(signup_password) < 8:
print('This password should be more than 8 characters. PLease enter your info again.')
exit()
if num_there(signup_password) == False:
print('This password has no number')
exit()
if num_there(signup_password) == True:
special_character_check(signup_password)
signup_confirm_password = input('Please confirm your password')
if signup_password == signup_confirm_password:
available_accounts_usernames.append(signup_username)
available_accounts_passwords.append(signup_password)
print('Your account has been created. Please login to access it.')
if signup_password != signup_confirm_password:
print("These passwords don't match. Please enter your info again")
exit()
content = available_accounts_usernames
content2 = available_accounts_passwords
with open('database.json', 'w') as f:
json.dump({'usernames': content, 'passwords': content2}, f)
More info at https://docs.python.org/3.9/library/json.html
You might want to use pickle files instead.
import pickle as pkl
# Write to file
with open("accounts.pkl","wb") as f:
pkl.dump(accounts, f) # accounts is the list
# Read the file
with open("accounts.pkl","rb") as f:
accounts = pkl.load(f)

Python: How to compare file context to user input

I have a Register.txt file in which I enter all user information such as username, email and password.
The content is written into the file as follows:
> emailadress, username, password;
That's my code:
import os
script_dir = os.path.dirname(__file__)
rel_path = 'Register.txt'
abs_file_path = os.path.join(script_dir, rel_path)
print('Welcome')
ExistingUser = input('Do you already have an Account y/n?: ')
def add_user(email, username, password):
file = open(abs_file_path, 'a')
file.write('> ' + email + ', ' + username + ', ' + password + ';\n')
file.close()
def check_password(userPassword, userName):
file = open(abs_file_path, 'r')
file_contents = file.read()
password = userPassword
Flag = 0
for i in file_contents.split('\n'):
if password == i:
Flag = 1
if Flag == 1:
print('Welcome back, ', userName)
else:
print('Something went wrong.')
if ExistingUser.lower() == 'n':
while True:
userEmail = input('email: ')
userName = input('username: ')
userPassword = input('password: ')
userPasswordConfirm = input('Confirm password: ')
if userPassword == userPasswordConfirm:
add_user(userEmail, userName, userPassword)
ExistingUser = 'y'
break
print('Passwords does NOT match!')
print('You have successfully registered!')
if ExistingUser.lower() == 'y':
while True:
userName = input('username: ')
userPassword = input('password: ')
check_password(userPassword, userName)
My Output looks in the Login section always like this: Something went wrong
If each line in the file looks like this
>>> line = '> emailadress, username, password;'
You need to separate it into its three parts before doing comparisons. First remove the unwanted characters at the beginning and the end.
>>> line = line[2:-1]
>>> line
'emailadress, username, password'
Then split the line on the commas.
>>> email,uname,password = line.split(', ')
>>> uname, password
('username', 'password')
>>> uname == 'username' and password == 'password'
True
>>>

Error on Python Json.load: Extra data line 10 column 2 (char 194)

I am new to python and am working on a project that require appending json data to a file data.txt after which i need to iterate over the data and filter email and password.
Here is my code
import json
from main import *
from jobs import *
def registration():
''' Register a user.'''
print('''Welcome! \nRegister to get started \n''')
data = {} # Container that wil hold user details before writing to a file
fullname = input('Full name: ')
email = input('Email address: ')
phone_number = input('Phone number: ')
password = input('Password: ')
# append to users dictionary
data['users'] = []
data['users'].append({
'Fullname': fullname,
'Email': email,
'Phonenumber': phone_number,
'Password': password
})
# appending to a file
with open('data.txt', 'a') as users_file:
json.dump(data, users_file, indent=4)
login()
def login():
''' Check if a user has registered and login the user after authentication'''
print('''Don't have an account yet?\n 1. Create account\n 2. Continue to login ''')
user_response = input()
if user_response == '1':
return registration()
with open('data.txt') as users_file:
data = json.load(users_file)
Email = input("email: ")
Password =input("Password: ")
for foo in data['users']:
if foo["Email"] == Email and foo["Password"] == Password:
x = foo["Email"]
y = foo["Password"]
x == y is True
#Creates a login session for a staff and saves it to session.txt
print (f"Welcome! logged in as {Email}")
keyword_post = input('1. Search job by keyword\n 2. Register a job')
if keyword_post == '1':
return keywords()
return job_list()
else:
print('Invalid email or password.')
return login()
I am getting raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 10 column 2 (char 194) error message whenever more than one user registered. Please i need help on how to resolve this.
You need a comma between each entry. It also doesnt make sense to have the key "users" repeated. That should be your key, then within that key, your list of user parameters/info
Couple of other things:
I'm not sure what this is doing for you:
x = foo["Email"]
y = foo["Password"]
x == y is True
I took it out as x == y will always return False, so I'm not sure why store as x and y variables, and x == y is True just doesn't make sense.
Another thing to consider is emails (unlike passwords) are not case sensitive, so you need to anticipate that. so someone should not be able to register USER#email.com and user#email.com...it's the same email address. So store emails as either all upper or lower case.
I made a few minor changes as well, doesn't change the logic, but added a few prints (If wrong password, if email already exists, etc.) You can also continue to add some checks in there too using regex. So things like, email address needs to be in the form of xxxx#xxxxxxx.com So if it doesn't have the # or .com, .edu, dot whatever, it'll not accept the email address. Or phone number needs to follow a certain pattern. But that you can do later, if needed.
You also don't NEED to 'user' key in there (unless you'll be adding some other key into the json later??) I'm not sure as I don't know what your end is to look like or be used for. It doesn't hurt to have it there though, so not a big deal, but it just adds another level that may or may not be needed.
Try this:
import json
import os
from main import *
from jobs import *
def registration():
#### Register a user ####
print('Welcome!\nRegister to get started\n')
inputdata = {} # Container that will hold user details before writing to a file
fullname = input('Full name: ')
email = input('Email address: ').lower()
phone_number = input('Phone number: ')
password = input('Password: ')
# append to users dictionary
inputdata['users'] = {}
inputdata['users'][email] = {}
inputdata['users'][email].update({
'Fullname': fullname,
'Phonenumber': phone_number,
'Password': password
})
# appending to a file
if os.path.isfile('data.txt'):
with open('data.txt', 'r') as users_file:
dataFile = json.load(users_file)
# Check if email already exists
if email in dataFile['users'].keys():
print ('Can not register this email. Email already in use.')
return login()
dataFile['users'].update(inputdata['users'])
with open('data.txt', 'w') as users_file:
json.dump(dataFile, users_file, indent=4)
else:
with open('data.txt', 'w') as users_file:
json.dump(inputdata, users_file, indent=4)
login()
def login():
''' Check if a user has registered and login the user after authentication'''
print('''Don't have an account yet?\n 1. Create account\n 2. Continue to login ''')
user_response = input()
if user_response == '1':
return registration()
with open('data.txt') as users_file:
data = json.load(users_file)
Email = input("Email: ").lower()
Password =input("Password: ")
userEmailList = list(data['users'].keys())
if Email not in userEmailList:
print ('Email is not registered.')
return login()
fooPassword = data['users'][Email]['Password']
if fooPassword == Password:
x = Email
y = fooPassword
x == y is True
#Creates a login session for a staff and saves it to session.txt
print (f"Welcome! logged in as {Email}")
keyword_post = input('1. Search job by keyword\n2. Register a job')
if keyword_post == '1':
return keywords()
return job_list()
else:
print('Invalid password.')
return login()

Python Login Script; Usernames and Passwords in a separate file

I'm looking for assistance to get my Python script to imitate a log-in feature while the credentials are stored in a separate file.
I got it to work from hard-coded Username and Password, and it also reads in a file, but I'm having some difficulty finding out how to link the two together.
Any assistance is appreciated.
The Python script is as follows:
print "Login Script"
import getpass
CorrectUsername = "Test"
CorrectPassword = "TestPW"
loop = 'true'
while (loop == 'true'):
username = raw_input("Please enter your username: ")
if (username == CorrectUsername):
loop1 = 'true'
while (loop1 == 'true'):
password = getpass.getpass("Please enter your password: ")
if (password == CorrectPassword):
print "Logged in successfully as " + username
loop = 'false'
loop1 = 'false'
else:
print "Password incorrect!"
else:
print "Username incorrect!"
I found this somewhere else that helped me read the file in, and it does print the contents of the text file, but I am unsure on how to progress from this:
with open('Usernames.txt', 'r') as f:
data = f.readlines()
#print data
for line in data:
words = line.split()
The text file contains the Usernames and Passwords in a format of: Test:TestPW Chris:ChrisPW Admin:AdminPW with each credential on a new line.
As I said previously, any help is appreciated!
Thanks.
You could start having a dictionary of usernames and passwords:
credentials = {}
with open('Usernames.txt', 'r') as f:
for line in f:
user, pwd = line.strip().split(':')
credentials[user] = pwd
Then you have two easy tests:
username in credentials
will tell you if the username is in the credentials file (ie. if it's a key in the credentials dictionary)
And then:
credentials[username] == password
import hashlib ,os
resource_file = "passwords.txt"
def encode(username,password):
return "$%s::%s$"%(username,hashlib.sha1(password).hexdigest())
def add_user(username,password):
if os.path.exists(resource_file):
with open(resource_file) as f:
if "$%s::"%username in f.read():
raise Exception("user already exists")
with open(resource_file,"w") as f:
print >> f, encode(username,password)
return username
def check_login(username,password):
with open(resource_file) as f:
if encode(username,password) in f.read():
return username
def create_username():
try:
username = add_user(raw_input("enter username:"),raw_input("enter password:"))
print "Added User! %s"%username
except Exception as e:
print "Failed to add user %s! ... user already exists??"%username
def login():
if check_login(raw_input("enter username:"),raw_input("enter password:")):
print "Login Success!!"
else:
print "there was a problem logging in"
while True:
{'c':create_username,'l':login}.get(raw_input("(c)reate user\n(l)ogin\n------------\n>").lower(),login)()
You should not use 2 loops. It would just tell the person that they guessed the username. Just saying. use one loop.
also check my repl.it it page for a better sso that can have like 100 people at once without else if statements
Here it is: https://repl.it/#AmazingPurplez/CatSSO
Has errors. Was developed only by me so +rep to me.
rep to: Joran Beasley
Could not post code here because of "indention errors" like frick it! but I will still try a simpler version
import getpass
username = "username"
password = "password"
loop = True
while loop == True:
userinput = input("question")
passinput = getpass.getpass("question")
if userinput == username and passinput == password:
statements
break
else:
statements
username = raw_input("Username:")
password = raw_input("Password:")
if password == "CHANGE" and username == "CHANGE":
print "Logged in as CHANGE"
else:
print "Incorrect Password. Please try again."

Categories