I want a user to be able to enter a new username and password and it saves it into the same file so it can be used for the login process that would come after. The user should be able to enter a new username into an input and the same for the password then it is saved to the file to be used later. I would do this myself but i don't know how to save it to the same file.
import time
import sys
uun = "test"
uun01 = "test01"
uun02 = "test02"
usernames = (uun+uun01+uun02)
upw = "test"
upw01 = "test01"
upw02 = "test02"
passwords = (upw+upw01+upw02)
max_attempts = 3
attempts = 0
while True:
print("Username")
username = input("")
print("Password")
password = input("")
if username in usernames and password in passwords:
print("Access Granted")
else:
attempts+=1
if attempts >= max_attempts:
print(f"reached max attempts of {attempts} ")
sys.exit()
print("Try Again (10 sec)")
time.sleep(10)
continue
break
First thing I do when deciding how to file data is think about how I want to access it later - this determines the data structure. A couple examples are, just straight key : value dictionary (username : password) to search by username or maybe entrytime : (username, password) to search by when the entry was made.
Once that is decided, format into a string and write to file. A simple print() of your data structure will show how it looks 'in the raw' and how you might want to format it for easy access later.
Related
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')
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()
def getlogins():
from requests import get
url = "https://raw.githubusercontent.com/Ezb2661/lol/master/loginstest"
return get(url).text
logins = getlogins()
logins = logins[:-1]
username = input("Username:")
username = str(username)
password = input("Password: ")
password = str(password)
if password == logins[username]:
print("Logged in!")
else:
print("Wrong password or username")
Whenever I run this, it does prompt for username and password, but then it says there is an error on line 15 of :
TypeError: string indices must be integers
Fixed this by fixing my json format to {"ezb2661": "test"} rather than {"ezb2661:test"}, and then using
return loads( get(url).text )
I am trying to fetch the contents of a page using Requests.The URL has 3 parameters:
Unique page ID
Username
Password
My initial block of code looks like this :
import requests
id = raw_input("Enter the unique id:")
user = raw_input("Enter your username:")
password = raw_input("Enter corresponding password:")
try:
r = requests.get('http://test.com/request.pl?id=' + id, auth=(user, password))
if r.status_code == 404:
print "No such page exists.Please check the ID and try again"
## Ask for input again
else:
print r.text
except requests.ConnectionError:
print "Server is refusing connections.Please try after sometime"
sys.exit(1)
My issue is on the commented line wherein i want the user to be prompted for the input again.How do I pass the control flow back to the top of the script.
I have a vague feeling that I might be doing this in a very crude way and there might be more elegant solutions using functions.If there are any,please do enlighten me.
This will do what actually you want.
import requests
def user_input():
id1 = raw_input("Enter the unique id:")
user = raw_input("Enter your username:")
password = raw_input("Enter corresponding password:")
try:
r = requests.get('http://test.com/request.pl?id='+ id1 + user + password)
if r.status_code == 404:
print "No such page exists.Please check the ID and try again"
## Ask for input again
user_input()
else:
print r.text
except requests.ConnectionError:
print "Server is refusing connections.Please try after sometime"
sys.exit(1)
user_input()
The simplest (but not necessarily the most extensible) way is to put everything in a while True loop.
import requests
while True:
id = raw_input("Enter the unique id:")
user = raw_input("Enter your username:")
password = raw_input("Enter corresponding password:")
try:
r = requests.get('http://test.com/request.pl?id=' + id, auth=(user, password))
if r.status_code == 404:
print "No such page exists.Please check the ID and try again"
## control flow will reach the bottom and return to the top
else:
print r.text
break
except requests.ConnectionError:
print "Server is refusing connections.Please try after sometime"
sys.exit(1) ## Exit condition of the loop
I would place this code in a while loop that always executes while True: and have a flag that allows you to break out of the loop appropriately.
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."