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

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.

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 login form with pandas not Working

I'm trying to make a login using my CSV file and i'm using pandas to read my csv file but i keep getting this error
AttributeError: 'DataFrame' object has no attribute 'brugernavn'
I can't seem to figured out if my csv file is setup wrong or my code ain't done correctly
import pandas as pd
class Login:
def Userlogin(self):
userData = pd.read_csv('Csv/Users.csv')
df = pd.DataFrame(userData)
print('Log ind\n')
user = input('Brugernavn : ')
pasw = input('Password : ')
matching_creds = (len(df[(df.brugernavn == user) & (df.password == pasw)]) > 0)
if matching_creds:
print('succes')
else:
print('kontakt admin')
LoginHandler = Login()
LoginHandler.Userlogin()
This is my CSV FILE
brugernavn;password;fornavn;efternavn;rolle;stilling
Val;1234;Valon;abc;1;Udvikler
Casper;1234;Casper;abc;1;Udvikler
Peter;1234;Peter;Blink;3;Teknikker
Grete;1234;Grete;Hansen;2;Administration
You need to specify that the csv is semicolon separated. I also fixed the password checker.
import pandas as pd
class Login:
def Userlogin(self):
userData = pd.read_csv('Csv/Users.csv', sep=';')
df = pd.DataFrame(userData)
print('Log ind\n')
user = input('Brugernavn : ')
pasw = input('Password : ')
# get index of username if it exists
index = df[df['brugernavn'] == user].index.values
# see if the password matches for that user
matching_creds = True if len(index) > 0 and str(df.at[index[0], 'password']) == pasw else False
if matching_creds:
print('succes')
else:
print('kontakt admin')
LoginHandler = Login()
LoginHandler.Userlogin()
As a side note, you never want to store passwords in plain text. You should store the hash of the password and compare the hashes.

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

Comparing variables from file

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

Categories

Resources