I am new in python and I am doing these kind of little projects so that I can build myself.
This is a little project which will only add and view the username and passwords with a master password. I was able to add username and passwords with encrypted the passwords in the file. But to view the passwords it shows me two problems in 23 and 39 line. And also the master password is not working.
from cryptography.fernet import Fernet
'''
def write_key():
key = Fernet.generate_key()
with open("key.key", "wb") as key_file:
key_file.write(key)'''
def load_key():
file = open("key.key", "rb")
key = file.read()
file.close()
return key
master_pwd = input("What is the master password? ")
key = load_key() + master_pwd.encode()
fer = Fernet(key)
def view():
with open('passwords.txt', 'r') as f:
for line in f.readlines():
data = line.rstrip()
user, passw = data.split("|")
print("User:", user, "| Password:",
fer.decrypt(passw.encode()).decode())
def add():
name = input("Account name: ")
pwd = input("Input password: ")
with open('passwords.txt', 'a') as f:
f.write(name + "|" + fer.encrypt(pwd.encode()).decode() + "\n")
while True:
mode = input("Would you like to add a new password or view existing ones?(Add/View):\nOtherwise press 'Q' to Quit: \n").lower()
if mode == "q":
break
elif mode == "view":
view()
elif mode == "add":
add()
else:
print("Invalid mode.")
continue
The problems are shown in this picture.
Related
I have a login program that hashes a string and stores it in a file to create a new account. When I need to log in, the login detail strings get hashed, and the program checks if the hashed strings have a match in the file. The program works without hashing, but when I hash the identical login details, the hash values are not the same. I have checked and the strings are exactly the same. Here is my code:
import tkinter
import math
import os
import hashlib
# The login function #
def login(username, password, file_path):
file_new = open(file_path, "a")
file_new.close()
file = open(file_path, "r")
file_content = file.read()
print(file_content)
file.close()
hashed_username = hashlib.md5(bytes(username, "utf-8"))
hashed_password = hashlib.md5(bytes(password, "utf-8"))
print(f"Hashed username: {hashed_username}, hashed password: {hashed_password}")
if f"{hashed_username},{hashed_password}" in file_content[:]:
return "You were logged in successfully"
else:
return "We could not find your account. Please check your spelling and try again."
# The account creation function #
def newaccount(username, password, file_path):
file_new = open(file_path, "a")
file_new.close()
# Reading the file #
file = open(file_path, "r")
file_content = file.read()
print(file_content)
file.close()
# Hashing the account details #
hashed_username = hashlib.md5(bytes(username, "utf-8"))
hashed_password = hashlib.md5(bytes(password, "utf-8"))
print(f"Hashed username: {hashed_username}, hashed password: {hashed_password}")
file_append = open(file_path, "a")
# Checking to see if the details exist in the file #
if f"{hashed_username},{hashed_password}" in file_content[:]:
file_append.close()
return "You already have an account, and were logged in successfully"
else:
# Writing the hashed details to the file #
file_append.write(f"{hashed_username},{hashed_password}\n")
file_append.close()
return "New account created."
logins_path = "Random Scripts\Login Program\logins.txt"
signin_message = input("Would you like to: \n1. Create an account \nor \n2. Log in\n")
if signin_message == "1":
print("User chose to create account")
newacc_username = input("Input a username: ")
newacc_password = input("Input a password: ")
print(newaccount(newacc_username, newacc_password, logins_path))
elif signin_message == "2":
print("User chose to log in")
username = input("Input your username: ")
password = input("Input your password: ")
print(login(username, password,logins_path))
else:
print("Please enter 1 or 2")
hashed_username = hashlib.md5(bytes(username, "utf-8"))
This function returns a hash object, and when you print it or write it to a file, you get something like this:
<md5 HASH object # 0x7f8274221990>
... which isn't terribly useful.
If you want the actual text of the hashes, call .hexdigest():
hashed_username = hashlib.md5(bytes(username, "utf-8")).hexdigest()
# returns e.g. "47bce5c74f589f4867dbd57e9ca9f808"
I am completely new to programming and started a few days ago with learning Python(v.3.8.8). I wanted to make a small password manager, but with a little secret function(I think that's not important and it would take too much time to describe). Anyways I converted the main.py to a .exe with auto-py-to-exe but every time I wanna execute the .exe I can only enter my Login data and the window instantly closes but in Pycharm everything works totally fine. Does anyone know why?
EDIT: It works now, there was no missing "Input()" or stuff like that, I had a spelling mistake in my code and pycharm ignored it!
from cryptography.fernet import Fernet
welcome = input("Login(1), New User (2): ")
def new_user(): # creates a new user and safe the Username and pw in a .txt
print("The login is just for the safety of your data, everything is stored on your local PC!")
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
key = Fernet.generate_key()
f = Fernet(key)
f.encypt(b'password')
file = open(username + ".txt", "w")
file.write(username + ":" + password)
#file.close()
login() # go to login after everything is safed in the .txt
else:
print("Passwords do NOT match!")
def login(): # checks if the entered username and pw match with the .txt content
login1 = input("Login:")
login2 = input("Password:")
file = open(login1 + ".txt", "r")
pw = file.readline()
#file.close()
if pw == login1 + ":" + login2: # infinte trys to enter the username and pw
print("Welcome " + login1)
pwrequest()
else: # returns to login() if the pw is incorrect
print("Incorrect username or password. Please try again")
login()
def pwrequest():
q = input("safe new Password(1), show safed passwords(2)")
if q == "2":
data() # show all saved pw
if q == "1":
newdata() # go to data() if the user want to add a new pw or
# want to acces the hidden part
def data():
file = open('1.txt', 'r') # prints all saved passwords
file_pw = file.read()
print(file_pw)
file.close()
c = input("Press (1) to delete something and press (2) to log out.")
if c == '1':
delete() # delete a pw or acces to hidden part
if c == '2':
login() # simple logout system, probably have to change this to something more intermediate
def newdata(): # safes the data in variables and put it in a .txt file
company = input("Enter the companys name: ")
username = input("Enter your username: ")
password = input("Enter your password: ")
print(company + username + password + ", is everything correct?")
a = input("y/n")
if a == "y":
file = open("1.txt", "w")
file.write(
"Company: " + company + "\n" + "Username: " + username + "\n" + "Password: " + password + "\n" + "\n")
file.close()
pwrequest() # return to pwrequest()
if a == "n":
newdata() # return to newdata() if something is incorrect
secretWord = "CompanyUsernamePassword" # define the secret word to finaly acces the hidden part
if company + username + password == secretWord:
secrettest() # go to secrettest() to enter the secret word
def delete(): # just simple code that delete specific content of the pw .txt
name = input("Please enter the Company, Username and password you wanna delete: ")
with open("1.txt", "r") as f:
lines = f.readlines()
with open("1.txt", "w") as f:
for line in lines:
if line.strip("\n") != name:
f.write(line)
def secrettest():
key = Fernet.generate_key()
f = Fernet(key)
truepass = f.encrypt(b"Test1234")
trys = 3
while trys != 0: # checks if you entered the correct pw and if not count 2 times
password = input("Pls enter the password: ")
d = f.decrypt(truepass)
if password == d.decode():
print(truepass)
break
else:
print("Wrong password!")
trys -= 1
if trys == 0:
print("You entered the wrong password to many times!")
if welcome == "1": # should probably try to move that to the top
login()
if welcome == "2": # this too
new_user()
I think I know why the .exe always closes. I executed the .exe in the windows cmd, and got this error "AttributeError: 'Fernet' object has no attribute 'enrcypt'". I'm kinda sure that this is the part that caused the trouble. I'm just wondering why pycharm just ignored this error...
I'm just starting with python and I want to make a simple login system with text files. Everytime I run the code I get this error. It doesn't even make the text file. Before this, I could run my code and it made a file but now it doesn't. I tried just one line of code to open a text file but that doesn't work either.(line of code: f = open("demofile.txt")) I also tried to google it, no solution. I don't know what to do?
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no, please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", 'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
f = open("dataBank.txt", 'w')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", "r")
info = f.read()
info = info.split()
if name in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
i dont know whats your logic but to create a file you need to use a w+
try it by de the code
def AskForAccount():
status = input("Do you have an account? ")
if status == "yes":
logIn()
elif status == "no":
createAccount()
else:
print("Type yes or no, please.")
AskForAccount()
def createAccount():
name = str(input("username: "))
password = str(input("password: "))
try:
f = open("dataBank.txt", 'r')
info = f.read()
if name in info:
return 'Name unavailable'
f.close()
except:
return 'Data base donest exists. creating one...'
f = open("dataBank.txt", 'w+')
info = info + ' ' + name + ' ' + password
f.write(info)
def logIn():
username = str(input("username: "))
password = str(input("password: "))
f = open("dataBank.txt", "r")
info = f.read()
info = info.split()
if username in info:
index = info.index(username)+1
usrPassword = info[index]
if usrPassword == password:
return "welcome back," + username
else:
return 'password incorrect'
else:
return 'Name not found'
print(AskForAccount())
The error you get in f = open('demofile.txt') is because open takes an additional argument 'mode' whose default value is 'r' for read. If the passed filename does not exist you get the described error.
Use f = open('demofile.txt','w') instead for writing to a file. This creates a new file if the filename does not exist.
I have problem to create a full coding python file handling. I need all data functions in python will be save in txt file. Below is my coding.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = int(input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top
Management (e.g 1/2/3/4): "))
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
serLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%li "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
Actually, this program should have five requirements. First is staffRegistration(), staffLogin(), staffAttendance(), staffLeaveApplication(), approval() but I have done for two requirements only and I get stuck at staffLogin(). I need every function will be save in txt file (I mean the data in function).
In line 32 you try to convert a String into Integer. Besides, in your main function, you have an unresolved variable userLogin.
The other problem is in line 43 (staffLogin function), You want to write a long integer but you pass a string. I have tried to fix your code except for userLogin in main.
def getListFromFile(fileName):
infile = open(fileName,'r')
desiredList = [line.rstrip() for line in infile]
infile.close()
return desiredList
def main():
staffRegistration()
staffLogin()
regList = getListFromFile("registration.txt")
createSortedFile(regList, "afterreg.out")
loginList = getListFromFile("login.txt")
createSortedFile(userLogin, "afterlogin.out")
checkFileRegistration()
checkFileLogin()
def checkFileRegistration():
print("\nPlease check afterreg.out file")
def checkFileLogin():
print("\nPlease check afterlogin.out file")
def staffRegistration():
regList = []
name = input("Name: ")
s = int(input("Staff ID (e.g 1111): "))
regList.append(s)
s = int(input("Staff IC (without '-'): "))
regList.append(s)
s = input("Department - 11:IT Dept 12:ACC/HR Dept 13:HOD 41:Top Management (e.g 1/2/3/4): ")
regList.append(s)
s = int(input("Set username (e.g 1111): "))
regList.append(s)
s = int(input("Set Password (e.g 123456): "))
regList.append(s)
f = open("registration.txt",'w')
f.write(name)
f.write(" ")
for info in regList:
f.write("%li "%info)
f.close
f1 = open("afterreg.out",'w')
f1.writelines("Registration Successful\n\n")
f1.close()
def staffLogin():
userLogin = input("\nProceed to login - 1:Login 2:Cancel (e.g 1/2): ")
if userLogin == "1":
username = input("\nUsername (e.g 1111): ")
l = int(input("Password: "))
if userLogin == "2":
print("\nLogin cancelled")
f = open("login.txt",'w')
f.write(username)
f.write(" ")
for info in userLogin:
f.write("%s "%info)
f.close
f1 = open("afterlogin.out",'w')
f1.writelines("Logged in successful")
f1.close()
def createSortedFile(listName, fileName):
listName.sort()
for i in range(len(listName)):
listName[i] = listName[i] + "\n"
outfile = open(fileName,'a')
outfile.writelines(listName)
outfile.close()
main()
There are a lot of problems in the staffLogin() function. e.g. the result of the first input()is bound to serLogin, but this should be userLogin.
If that is corrected, a password is read from the user, but nothing is ever done with it. Should the password be treated as an integer?
Also, if the user enters 2 at first prompt, the code will not set username but it will still try to write username to the file. That will raise a NameError exception.
Finally, the code attempts to write the characters in userLogin to the file as though they are integers. Not only will that not work, it doesn't make sense. Perhaps this should be writing the password to the file?
How to I make it so in the code below when you register a username and password it it adds a new line to the txt files and when you login it checks every line in the txt files sepretly
and declaring it as correct if any of the lines match the login instead of it checking if the username and password matches the whole thing
print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for
register: ")
if option == "R":
print "Warning Only 1 user can be registered"
usernamer = raw_input("Desired Username: ")
passwordr = raw_input("Desired Password: ")
file = open("Username.txt","w")
file.write(usernamer + '\n')
file.close()
file = open("Password.txt","w")
file.write(passwordr + '\n')
file.close
print "Registered"
else:
usr = raw_input("Username: ")
pss = raw_input("Password: ")
file = open("Username.txt","r")
if usr == file.read():
print "Username correct"
file.close()
else:
print "Username incorrect or not registered"
file.close()
file = open("Password.txt","r")
if pss == file.read():
print "Password correct"
file.close()
else:
print "Password incorrect or not registered"
file.close()
Here is how to find whether a string exists in some line of a file:
contain = False # Indicator of whether some line of a file contains the string
with open(FILENAME, 'r') as file: # Use `with` statement to automatically close file object
for line in file:
if string in line:
contain = True
break
I have modified your code to validate password and username with a password check logic. This should work.
print "Welcome to UserName and Password Test"
option = raw_input("Would you like to login or register L for Login R for register: ")
if option == "R":
print "Warning Only 1 user can be registered"
usernamer = raw_input("Desired Username: ")
passwordr = raw_input("Desired Password: ")
file = open("Username.txt","a")
file.write(usernamer + '\n')
file.close()
file = open("Password.txt","a")
file.write(passwordr + '\n')
file.close
print "Registered"
else:
usr = raw_input("Username: ")
pss = raw_input("Password: ")
file = open("Username.txt","r")
count = 0
userfound = False
try:
for user in file.readlines():
count += 1
if usr == user.strip():
userfound = True
file.close()
if not userfound:
raise
file = open("Password.txt","r")
passcount = 0
for passcode in file.readlines():
passcount += 1
if count == passcount:
if pss == passcode.strip():
print 'successfully logged in'
else:
print "Password incorrect or not registered"
break
file.close()
except Exception as e:
print 'User login error !!!'
If you just want to check if the user is in the file contents,
if usr in file.read():
do_somethin
"==" checks if the value are same as it is, "in" keyword checks if the substring is in the huge string. In file.read() will have the whole contents as a string.