Comparing variables from file - python

script is in python and it is used to create a file that saves username and password, I understand that there are flaws in the overall script but I want to know:
when script is executed, a username and password is saved into a file separated with ','. each line is a start of a new username. When login function is called, the list is searched and compared with the entered username, after found is positive: password is checked and this is where my script doesn't work as intended.
Why can't I get a positive when comparing 2 variables (for password in login function), they should be identical.(note y, is the line read from file of usernames & passwords, where the first element is username and second password)
def function():
username=input('enter username')
password=input('enter password')
file=open('users1','a')
file.write(username + ',' + password +'\n')
def login():
user=input('username')
passw=input('password')
file=open('users','r')
searchline=file.readline()
for line in file:
if user in line:
x=line
y=x.split(',')
print(y[1])
if user == y[1]:
print('access confirmed')
else:
print('pass=', y[1])
function()
login()

The file you writing to and reading from have different names (users1 and users). Each line read from the file has an end of line character (\n) need to strip that out before comparing the passwords.
def function():
username = input('enter username')
password = input('enter password')
file = open('users','a')
file.write(username + ',' + password + '\n')
def login():
username = input('username')
password = input('password')
file = open('users','r')
for line in file:
if username in line:
y = line.rstrip().split(',')
print(y[1])
if password == y[1]:
print('access confirmed')
else:
print('password =', y[1])
function()
login()
checkout the python documentation on rstrip

Related

Python following tutorial but it gives me the error: "(" was not closedPylance

I am trying to make a registration / login form in Python following a tutorial but I get this error with the exact same code.
The code:
import hashlib
def signup():
email = input(“Enter email address: “)
pwd = input(“Enter password: “)
conf_pwd = input(“Confirm password: “) if conf_pwd == pwd:
enc = conf_pwd.encode()
hash1 = hashlib.md5(enc).hexdigest() with open(“credentials.txt”, “w”) as f:
f.write(email + “\n”)
f.write(hash1)
f.close()
print(“You have registered successfully!”) else:
print(“Password is not same as above! \n”)def login():
email = input(“Enter email: “)
pwd = input(“Enter password: “) auth = pwd.encode()
auth_hash = hashlib.md5(auth).hexdigest()
with open(“credentials.txt”, “r”) as f:
stored_email, stored_pwd = f.read().split(“\n”)
f.close() if email == stored_email and auth_hash == stored_pwd:
print(“Logged in Successfully!”)
else:
print(“Login failed! \n”)while 1:
print("********** Login System **********")
print("1.Signup")
print("2.Login")
print("3.Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
signup()
elif ch == 2:
login()
elif ch == 3:
break
else:
print("Wrong Choice!")
It gives me the error "(" was not closedPylance at this part:
email = input(“Enter email address: “)
Also, can I use this code to make a registration / login form with easygui in my existing code?:
active = True
while active:
username = enterbox(text2, title)
menu_choice = choicebox(text, title, menu)
message = "Geselecteerd: " + menu_choice
room_choice = choicebox(message, title, rooms)
message = "Geselecteerd: " + room_choice
day_choice = choicebox(message, title, days)
message = "Geselecteerd: " + day_choice
time_choice = choicebox(message, title, times)
message = "Geselecteerd: " + time_choice
active = ynbox("Uw afspraak is bevestigd. Wilt u terug gaan naar het hoofdmenu?", title2, button_text)
with open("reserveringen.txt", "w") as f:
f.write(f"Personeelsnummer: {username}\n")
f.write(f"Vergaderruimte: {room_choice}\n")
f.write(f"Dag: {day_choice}\n")
f.write(f"Tijd: {time_choice}\n")
times.remove(time_choice)
Changing the "" but it didn't work.
Looks like you have copied and pasted some code:
Anywhere you see these weird looking quotation marks, replace with these: "
i.e The ones next to the enter key
Your code is riddled with the weird quotation marks - you need to replace them all.
Note:
And finally, I noticed that you have some weird indentation issues.
In python, indentation matters, so your if-statement and with statement and def login(): etc etc and a few other statements, need to be fixed up.

Encrypted string doesn't give same value as identical string python

I'm writing a password manager program, and I need to store an encrypted string in a file. (The "service" variable) When the user needs to retrieve the information, they enter the same string as before. When I encrypt the same string, I get a different output. I've checked multiple times, and the string is the same. Anyone know of a fix for this?
Code I'm using to encrypt and write to the file:
def new_account(service, username, password, filepath, key):
# Encrypting the account details #
encrypted_service = key.encrypt(bytes(service, "utf-8"))
encrypted_username = key.encrypt(bytes(username, "utf-8"))
encrypted_password = key.encrypt(bytes(password, "utf-8"))
encrypted_service = encrypted_service.decode("utf-8")
encrypted_username = encrypted_username.decode("utf-8")
encrypted_password = encrypted_password.decode("utf-8")
password_file = open(f"{filepath}\passwords.txt", "a")
password_file.close()
password_file = open(f"{filepath}\passwords.txt", "r")
password_file_content = password_file.read()
password_file.close()
password_file = open(f"{filepath}\passwords.txt", "a")
if f"{encrypted_service},{encrypted_username},{encrypted_password}" in password_file_content:
password_file.close()
return("The account already exists.")
else:
password_file.write(f"{encrypted_service},{encrypted_username},{encrypted_password}\n")
password_file.close()
return f"Account saved for {service.title()} with username {username} and password {password}."
Code I'm using to retrieve the information:
# The account retrieval function #
def get_account(service, filepath, key):
encrypted_service = key.encrypt(bytes(service, "utf-8"))
encrypted_service = encrypted_service.decode("utf-8")
password_file = open(f"{filepath}\passwords.txt")
lines = password_file.read().split("\n")
word = f"{encrypted_service}"
# Getting the line with the account details #
for i in lines:
index = lines.index(i)
myline = lines[index]
encrypted_account_content = myline.split(",")
print(encrypted_account_content)
print(f"service is: {encrypted_service}")
if encrypted_account_content.count(encrypted_service) != 0:
# Decrypting the account details #
username = encrypted_account_content[1]
decrypted_username = key.decrypt(bytes(username, "utf-8"))
decrypted_username = decrypted_username.decode("utf-8")
password = encrypted_account_content[2]
decrypted_password = key.decrypt(bytes(password, "utf-8"))
decrypted_password = decrypted_password.decode("utf-8")
return f"Service: {service.title()}\nUsername: {decrypted_username}\nPassword: {decrypted_password}"
else:
return "Account not found. Please try again."
Any proper encryption will use randomization, so that the result will always be different, and you won't be able to tell that the plaintext was the same. That's needed to achieve semantic security. In practice, initialization vectors and modes of operation like CBC or CTR are used. The cryptography library you're using does it out of the box (with CBC mode).
You will either have to store service as a plaintext, which shouldn't significantly reduce the overall security, or decrypt each service field in order to find the needed record.

Python: Removing duplicate strings and staying within certain parameters

Currently, I am designing a credential database meant to hold a servername, username, and password in a text file. However, for the servername and passwords I am trying to make them unique (no two credentials / logins can have the same servername AND password, usernames can be duplicated).
For example,
# This is NOT acceptable because the servername is duplicated.
servername : username : password
google : john : 123
google : john : 321
# This is acceptable because the servername and password are unique.
servername : username : password
google : john : 123
yahoo : john : 321
I have searched stackoverflow for some answers but I was not able to find exactly what I am looking for. In my program's current state, when credentials are entered, they are simply listed right underneath the existing one and continue to add each additional credential without checking for duplicates.
# Creates the file "passdatabase.txt" for use with this code.
with open('passdatabase.txt', 'a+') as searchfile:
searchfile.close()
# Here I initialize the variable / count for the while loop
x = 1
print("\n======================="+
"\nYou chose to add a credential."
"\n-----------------------")
# User enters in a server name to be saved.
addservername = input("Server Name: ")
# User enters in a username to be saved.
addusername = input("Username: ")
# User enters in a password to be saved.
addpassword = input("Password: ")
# All inputs are combined to create a single variable in the format (servername : username : password)
addCredential = addservername + " : " + addusername + " : " + addpassword
# Loops until the user enters a valid submission (either [y] or [n]) to confirm information.
while x == 1:
# Input information is displayed for user to confirm.
confirmCredential = input("~~~~~~~~~~~~~~~~~~~~~~~" +
"\nPlease verify the entered credentials.\n" +
"\nServer Name: [" +
addservername + "]" +
"\nUsername: [" +
addusername + "]" +
"\nPassword: [" +
addpassword + "]" +
"\n\nIs the information correct? (y/n): ")
print("~~~~~~~~~~~~~~~~~~~~~~~")
if confirmCredential == "y":
x = 2
with open('passdatabase.txt', 'r') as searchfile:
lines_seen = set(open('passdatabase.txt'))
for addCredential in (searchfile, 1):
if addCredential not in lines_seen:
with open('passdatabase.txt', 'a+') as searchfile:
# I set the format of the credential to save in the text file as
# servername : username : password.
searchfile.write("\n" + addservername + " : " + addusername + " : " + addpassword)
print("[!] SUCCESS! Your credentials have successfully been stored [!]" +
"\n=======================")
# This breaks the for loop so it does not continue the code.
break
else:
print('Duplicate credential detected!')
elif confirmCredential == "n":
x = 2
print("[!] Your credentials have not been stored [!]" +
"\n=======================")
else:
print("###########################################################" +
"\n[!!!ERROR!!!] PLEASE ENTER EITHER [y] OR [n]. [!!!ERROR!!!]\n" +
"###########################################################")
My questions / requests in one simple list are as follows:
- How do I ensure that the user can only enter in unique entries for their servername and password credentials while allowing duplicate username entries?
- If a duplicate is detected, I would like the code to stop from going further and ask the user for input again until a proper unique credential is provided.
- Should I be using a set or an array? (Data-order does not matter)
- I've seen quite a few duplicate checking scripts that involve the use of 2 .txt files, is this possible with only 1?
- In the future I plan on adding encryption to the password entries, password strength checker, and possibly a credential log (of who has logged in).
- Any input is welcome as I am always willing to learn!
I am fairly new to Python coding and I would really just like some guidance on what I should be looking into next, I'm honestly not sure if I am even headed in the right direction.
Thanks
Maybe you should use sqlite instead of pure text file.
If you really want to implement database feature in a txt file:
Use set for tuple(servername, password), check if exist before appending to file. Remember to load all exist ones from your txt file before ask user to input.
You'd better use a file lock to make sure that only one instance of your script run at the same time.

Problem with concatenating strings/ getting value from file

I have been writing a program that saves passwords in hash form, but I am trying to get a value from within my file which stores a value for the salt. For some reason, it doesn't seem to work.
Here is my code:
hashpass = hashlib.sha256()
salt = ['hbjGVY0Kj07,kbjgvhjb,ZsGhnBi0lp]
for line in login:
usr = input()
pas = input()
log = line.split(',')
if usr in line:
x = line
salt_num = int(x[2])
setpass = str(pas + salt[salt_num])
hashpass.update(setpass.encode('utf-8'))
I have tried everything, but still no results when I concatenate the string, I just get the value of pas
Here is what I tried and it works. The code you have shared has some issue that I would request you to cross check with original code.
import hashlib
hashpass = hashlib.sha256()
salt = ['hbjGVY0Kj07','kbjgvhjb','ZsGhnBi0lp']
login = ["user,68a782faf939dfa370345934d255101926b7f59b3a65ab7db5b0bc6f78ec25e5,0"]
for line in login:
#print(line)
usr = input() # I input "user"
pas = input() # I input "qwerty"
log = line.split(',')
#print(log)
if usr in line:
x = log
salt_num = int(x[2])
setpass = str(pas + salt[salt_num])
print(setpass)
hashpass.update(setpass.encode('utf-8'))
OUTPUT --> qwertyhbjGVY0Kj07
Things I would suggest you to check:
All the items in list salt are in quotes, i.e., as string.
Login is a list of strings having elements with comma separated value, like I have created.
change x=line to x=log inside if condition.
I have fixed the issue, but am getting different errors when comparing the variable hashpass with log[1], when comparing my program claims that the password is wrong, here is the whole program for reference.
login = open('login.csv','r')
def logging():
atmptcount = 0
while atmptcount < 3:
usr = input('Please enter your username: ')
pas = input('Please enter your password: ')
hashpass = hashlib.sha256()
for line in login:
log = line.split(',')
if usr.upper() in line:
print(log[2])
salt_num = int(log[2])
setpass = str(pas + salt[salt_num])
hashpass.update(setpass.encode('utf-8'))
if usr == log[0] and hashpass.hexdigest() == log[1]:
print('correct')
return True
print(hashpass.hexdigest())
print(log[1])
atmptcount = atmptcount + 1
print('Sorry you have entered your details incorrectly, please try again')
login.seek(0)
print('Sorry, you have reached your maximum login attempts!')
return False
I have changed the variable names a bit but its the saem concept

When loading pickle, get import error, "no module named sip"

I am making a program in python that allows you to change the password. Here is the part that let's you change the password:
def done_clicked(self):
password_filea = open("password.pkl", "r")
password_check = pickle.load(password_filea)
username_filea = open("username.pkl", "r")
username_check = pickle.load(username_filea)
if self.currpword.text() == password_check and self.reppword.text() == password_check and self.curruser.text() == username_check and self.repuser.text() == username_check:
password_filea.close()
username_filea.close()
password_file = open("password.pkl", "wb")
username_file = open("username.pkl", "wb")
pickle.dump(self.newpword.text(), password_file)
pickle.dump(self.newuser.text(), password_file)
password_file.close()
username_file.close()
easygui.msgbox("Password Changed")
And here is the part that loads the username and password to let you sign in:
def sign_in_clicked(self):
password_file = open("password.pkl", "rb")
password = pickle.load(password_file)
username_file = open("username.pkl", "rb")
username = pickle.load(username_file)
print username
if self.pword.text() == password and self.username.text() == username:
MainWindow.show()
myWindow.hide()
else:
easygui.msgbox("Wrong Password!")
password_file.close()
username_file.close()
When I type in anything, I get this error:
line 154, in sign_in_clicked
password = pickle.load(password_file)
ImportError: No module named sip
How do I fix it? Please note that both these functions are under separate classes. Also, it works perfectly when I do it from a separate file, but when it does it from the same file, as it does in the example, it gives me the error. I am importing Cpickle. Thanks in advance.

Categories

Resources