I'm am trying to verify users using a text document but not having much success. Can someone please point me in the right direction? Here is my code. What I want to do is have have python look on the line which contains the hash and then verify the hash. It is able to verify the first hash but nothing after that. Does anyone know how to fix this?
def passwordVerify():
global hashOne
f = open("maindata.txt")
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
numberOne = userConfirm + 2
numberTwo = userConfirm + 1
for line in islice(f, numberTwo, numberOne):
hashOne = line
hashStripped = str.rstrip(hashOne)
hashchecker = sha256_crypt.verify(passWord, hashStripped)
f.close()
if hashchecker is True:
loggedIn()
else:
print "Please try again!"
time.sleep(2.5)
userLogin()
def userRegister():
screenClear()
print "!King of Hearts Registration System!"
realName = raw_input("What is your real name: ")
userName = raw_input("Choose a Username: ")
passWord = getpass.getpass("Please enter a password: ")
passHash = sha256_crypt.encrypt(passWord)
writeUser = "\n" + userName + "\n"
writePass = passHash
userDB = open("maindata.txt", "a")
userDB.write(str(writeUser))
userDB.write(str(writePass))
userDB.close()
print passHash
userLogin()
Related
I'm new to python, an I decided to write a simple password manager to learn. I'm having trouble retrieving one of the values out of the dictionary.
The function add_password write a key with 2 values (user, and password (encrypted))
And the function get_password read the key and supposed to get the values.
I can't get it to pull the value of user.
I have tried multiple methods, but so far no luck.
https://github.com/ae3erdion/Password_Manager/blob/main/main.py
import base64
import os
import string
import random
from unittest import TestCase
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
characters = list(string.ascii_letters + string.digits + "!##$%^&*()")
site = ""
user = ""
password = ""
password_file = {}
encrypted = ""
# Generate key for encryption
def generate_key():
password = input ("Enter password: ")
password = bytes(password, 'utf-8')
salt = b'\xceN\x01s\xabE\x15\x02\xd9pz(1\t\xbc4'
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=390000,
)
global key
key = base64.urlsafe_b64encode(kdf.derive(password))
# Check for the encryption key hash file exists and validate if the key is the same
if os.path.exists('password.hash'):
with open('password.hash', 'rb') as f:
key_validation = f.read()
if key_validation == key:
print("What would you like to do: ")
menu()
else:
print("Wrong password ")
exit
# If key hash file doesnt exist it create the file and write the encryption key hash to it
else:
with open('password.hash', 'wb') as f:
f.write(key)
with open('password.encode', 'wb') as f:
print("What would you like to do: ")
menu()
# Randon password generator
def generate_password():
length = int(16)
random.shuffle(characters)
random_password = []
for i in range(length):
random_password.append(random.choice(characters))
random.shuffle(random_password)
random_password = ("".join(random_password))
print(random_password)
# Write a new password to the pasword file
def add_password(site, user, password_site):
password_file[site] = password_site
with open('password.encode', 'a+') as f:
encrypted = Fernet(key).encrypt(password_site.encode())
f.write(site + " " + user + ":" + encrypted.decode() + "\n")
# Read password file and get the password
def get_password(site):
with open('password.encode', 'r') as f:
for line in f:
site, encrypted = line. split (":")
password_file[site] = Fernet(key).decrypt(encrypted.encode()).decode()
return password_file[site]
# Check for all files.
def main():
if os.path.exists('password.hash') & os.path.exists('password.encode'):
print ("Welcome Back!")
generate_key()
else:
print ("""
Welcome!
Create password""")
generate_key()
# Menu of options
def menu():
print("""
(1) Generate random password
(2) Add new password
(3) Get login information
(q) Quit""")
done = False
while not done:
choice = input("Enter choice: ")
if choice == "1":
generate_password()
elif choice == "2":
site = input("Enter the site: ")
user = input("Enter User: ")
password = input("Enter the password: ")
add_password(site, user, password)
elif choice == "3":
site = input("Enter site: ")
print(f"Your login information for {site} is ({get_password(site)})")
elif choice == "q":
done = True
print("Bye!")
else:
print("Invalid Choice")
if __name__== "__main__":
main()
If you change you get_password function to:
def get_password(site):
with open('password.encode', 'r') as f:
for line in f:
site, encrypted = line.split (":")
site, user = site.split()
password_file[site] = (user, Fernet(key).decrypt(encrypted.encode()).decode())
return password_file[site]
and change option 3 in your menu function
elif choice == "3":
site = input("Enter site: ")
user, passwd = get_password(site)
print(f"Your login information for {user}#{site} is ({passwd})")
You will still want to implement some error checking but that should will at least get you started.
I am trying to write a login function using python. However, I can't seem to write the code for checking the username and password against the ones stored in a file. The specific error is NameError: name 'adusername' is not defined. How do I fix this?
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.write(adusername)
adfile.write(",")
adfile.write(adpassword)
adfile.write("\n")
adfile.close()
def adminverification():
adun = input("Enter your username:")
adpw = input("Enter your password:")
adinfo = open("adlogindetails.txt", "r")
for line in adinfo:
adun, adpw = line.split(",")
if adun == adusername and adpw == adpassword:
print("Login successful!")
adminoptions()
else:
print("Incorrect username/password")
roleselection()
adminverification()
You have not declared adusername and adpassword in adminverification(). So, it is causing the error. If you want to use the variables from adminlogindetails(), change the variables name since you have stored the details in adlogindetails.txt.
The below code should be changed as line variable contains the already stored username and password:
adun, adpw = line.split(",")
Change above piece of code to the shown below:
adusername, adpassword = line.split(",")
you can use this:
def adminlogindetails():
adusername = input("Admin Username: ")
adpassword = input("Admin Password: ")
adfile = open("adlogindetails.txt", "a")
adfile.writelines(adusername + ',' + adpassword )
adfile.close()
def adminverification():
adun = input("Enter your username:").strip()
adpw = input("Enter your password:").strip()
with open("adlogindetails.txt", "r") as f:
lines = f.readlines()
i = 0
for line in lines:
adusername, adpassword= line.split(",")
adusername = str(adusername).strip()
adpassword = str(adpassword).strip()
if (adun == adusername) and (adpw == adpassword):
print("Login successful!()")
adminoptions()
break
else:
i += 1
if i >= len(lines): #If no any match upto last line, this will be true
print("Incorrect username/password")
roleselection()
break
adminverification()
First of all you are not calling adminlogindetails().
Also adusername is a local variable and you should either make it global using global adusername in the adminlogindetails function or declare it outside of the functions in the global scope.
See this - https://www.w3schools.com/python/python_scope.asp
This line is your problem:
adun, adpw = line.split(",")
"adun" and "adpw" are your inputs and you are overwriting them. Replace with this and it will be ok:
adusername, adpassword = line.replace("\n", "").split(",")
Note: "\n" needs to be removed for your comparison to be ok.
i am trying to make a simple login system for python. i tried several things using break,return. but i cant get pass the login system using the second line in the text file onwards. i can only login through the first line of the text file, i took the code fro an other question but didnt know how to get it to work so i tried to change it so i could understand how it can work. I am extremely new to python. please let me know where i got wrong and how i can change it to get it to work!
format for user.txt is
first name|last name|occupation|id|username|password
John|goh|worker|1|admin|1234
import datetime
def check():
x = 0
users = open("users.txt").read().split("\n")
for i in range(len(users)): users[i] = users[i].split("|")
while (x < 3):
username = str(input("Username: \n"))
password = str(input("Password: \n"))
f = open('project_AI.txt', 'a')
f.write(str(datetime.now()))
f.write('\n' + username + '\n')
f.write(password + '\n')
f.close()
for user in users:
uname = user[4]
pword = user[5]
if uname == username and pword == password:
print("Hello " + user[1] + ".")
print("You are logged in as: " + user[2] + '.')
x += 3
else:
print('error')
check()
x += 1
return
check()
many thanks!!
I think the "return" in the penultimate line is at the wrong indentation, and isn't really needed at all.
As soon as python touches a return, it instantly destroys the function. In your code, after every user it checks, it hits the return. Meaning it will never even reach the second user.
You also want to not use check() within the function, as it will create a clone of itself within itself. The while x < 3 will go through the logic multiple times for you.
import datetime
def check():
x = 0
users = open("users.txt").read().split("\n")
for i in range(len(users)): users[i] = users[i].split("|")
while (x < 3):
username = str(input("Username: \n"))
password = str(input("Password: \n"))
f = open('project_AI.txt', 'a')
f.write(str(datetime.now()))
f.write('\n' + username + '\n')
f.write(password + '\n')
f.close()
for user in users:
uname = user[4]
pword = user[5]
if uname == username and pword == password:
print("Hello " + user[1] + ".")
print("You are logged in as: " + user[2] + '.')
x += 3
return
print('error')
x += 1
check()
Hey I am trying to create a system using text files where a user can sign up and log in. All the data will be stored in plain text in a text file called User_Data.txt. My code works but I would like to know if there is anything I missed or If I could improve it in any way. Sorry for the Bad code Formatting in advance.
def choices():
print("Please choose what you would like to do.")
choice = int(input("For Sigining Up Type 1 and For Signing in Type 2: "))
if choice == 1:
return getdetails()
elif choice == 2:
return checkdetails()
else:
raise TypeError
def getdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
if name in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("User_Data.txt",'w')
info = info + " " +name + " " + password
f.write(info)
def checkdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
info = info.split()
if name in info:
index = info.index(name) + 1
usr_password = info[index]
if usr_password == password:
return "Welcome Back, " + name
else:
return "Password entered is wrong"
else:
return "Name not found. Please Sign Up."
print(choices())
There is a lot of improvements You could do.
First of all, split functionality to smaller function.
PASSWORD_FNAME = "User_Data.txt"
def get_existing_users():
with open("r", PASSWORD_FNAME ) as fp:
for line in fp.readlines():
# This expects each line of a file to be (name, pass) seperated by whitespace
username, password = line.split()
yield username, password
def is_authorized(username, password):
return any((user == (username, password) for user in get_existing_users())
def user_exists(username):
return any((usr_name == username) for usr_name, _ in get_existing_users())
# above is equivalent of:
#
# for usr_name, _ in get_existing_users():
# if usr_name == username:
# return True
# return False
def ask_user_credentials():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
return name, password
def checkdetails():
name, password = ask_user_credentials()
if is_authorized(name, password):
return "Welcome Back, " + name
if user_exists(name):
return "Password entered is wrong"
return "Name not found. Please Sign Up."
def getdetails():
name, password = ask_user_credentials()
if not user_exists(name):
return "Name Unavailable. Please Try Again"
# Not sure tho what would You like to do here
It's always good to remember to always close your file if you read it.
So if you do something like:
f = open("r", "file.txt") remember to always call f.close() later.
If you use context manager and do it like:
with open("r", "file.txt") as fp:
print(fp.read())
it will automatically close the file for you at the end.
Firstly, fix the spelling error at int(input("For Sigining Up Type 1") Other than that I would add some kind of purpose, for example storing secret numbers or something.
For example you can extend your script with a simple password recovery system.
I think it could be useful to learn...
You can implement a sort of a simple hashing system in order to avoid saving the password as plain text.
If you want to add a GUI, please consider using Tkinter.
https://docs.python.org/3/library/tkinter.html
Let we know.
Good Luck and Keep Coding with <3
import csv
name = input(': ')
password = input(': ')
age = input(': ')
hello = [name, password, age]
length = len(hello[0])
with open('db.csv', 'a') as testfile:
csv_writer = csv.writer(testfile)
for y in range(length):
csv_writer.writerow([x[y] for x in hello])
When I run the code above on a separate python file alone it works but whenever I try to put it in my full code it doesn't work.
What I am trying to do is basically make a register that when I put input it writes to the csv file. I also added a captcha thing for verification because why not.
csv_writer.writerow([x[y] for x in hello]):
Line 33 ^
The full code v
import random
import csv
def reg2():
print('wip')
def reg1():
ok = False
while not ok:
try:
name = input('Enter your name: ')
age = int(input('Enter your age:'))
password = input('Enter your password: ')
confirm = input('Confirm Password: ')
if confirm == password:
alphabet =''.join(random.choice('0PQRSTUVefghij56789WXYZabcdABCDEFCDrstuvwEFGJ234NOKLMkHImnopqxyz') for i in range(7))
print(alphabet)
captcha = input('Enter the words shown above (Not Case Sensitive): ')
if captcha.capitalize() == alphabet.capitalize() or 'admin'.capitalize():
print('Name: ' + name)
print('Age: {}'.format(age))
print('Password: ' + password)
option = input('Enter No to register again. Enter Yes to login.')
if option.startswith('N') or option.startswith('n'):
reg1()
elif option.startswith('Y') or option.startswith('y'):
hello = [name, password, age]
length = len(hello[0])
with open('db.csv', 'a') as testfile:
csv_writer = csv.writer(testfile)
for y in range(length):
csv_writer.writerow([x[y] for x in hello])
else:
captcha = input('Try again: ')
if captcha == alphabet:
print('Confirmed. ')
else:
print('You have tried too many times. Please register again.')
reg1()
else:
print('Your password is incorrect. Please register again.')
except ValueError:
print('Error 666: Please register again.')
reg1()
How do I fix this?
The full traceback error is http://pastebin.com/zshHji8i
[...]
length = len(hello[0])
with open('db.csv', 'a') as testfile:
csv_writer = csv.writer(testfile)
for y in range(length):
csv_writer.writerow([x[y] for x in hello])
So here, "length" is the number of characters in the name variable, a few lines later, for y in range(length) you're "enumerating" the letters, say you have 6 letters you're getting 0, 1, 2, 3, 4, 5 in y. A line later [x[y] for x in hello] you're asking for the letter y for the name, password, age, that has no sense for me.
What about a simple:
name = input(': ')
password = input(': ')
age = input(': ')
hello = [name, password, age]
with open('db.csv', 'a') as testfile:
csv.writer(testfile).writerow(hello)
Oh, and "hello" is a badly chosen name (we can't deduce what it contains). Oh and "x", "y", and "length" are badly chosen too, (length of what ?). Just choose a nice name for your variables and your bug will become obvious.
Why don't you just write:
with open('db.csv', 'a') as testfile:
csv_writer = csv.writer(testfile)
csv_writer.writerow(hello)
hello is already a list, there is no need for the construction you used.