Problem with concatenating strings/ getting value from file - python

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

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.

How do I break an inner for loop every time a condition is satisfied?

Good afternoon,
Im very new to python coding and Im trying to write a very basic md5 brute force password cracker for a school project.
I am supposed to write a script that will crack a series of MD5 hashed passwords. The passwords must be read in from a text file named “hashes.txt”, with one password on every line. The script should then start generating passwords, starting with single character, and then two characters, etc
My thought process of how to make a brute force cracker is as follows:
import hashlib
import itertools
abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#0123456789"
abc_list = list(abc)
def combo():
md5_hash = ""
file_name = open("hashes.txt", "r")
for password in file_name:
password = password.strip()
#print(password)
for r in range(len(abc_list)):
combinations_object = itertools.combinations(abc_list, r)
combinations_list = list(combinations_object)
#print(combinations_list)
for lis in combinations_list:
glue = "".join(lis)
hash_object = hashlib.md5(glue.encode())
md5_hash = hash_object.hexdigest()
print(glue)
#print(md5_hash)
#print(glue + " " + md5_hash)
if md5_hash == password :
print("Your password is: " + "'" + glue +"' "+ md5_hash)
break
The passwords I am given to crack are:
Z,
AD,
God,
1234,
AbCdE,
Trojan
Every time I run the script it only outputs the password: Z and then runs through the rest without fulfilling the 'if' statement.
I have tried using the 'break' statement under the 'if' but the outcome is the same.
You might benefit from creating and storing the combinations list once (or rather, a generator).
https://stackoverflow.com/a/31474532/11170573
import itertools
def all_combinations(any_list):
return itertools.chain.from_iterable(
itertools.combinations(any_list, i + 1)
for i in range(len(any_list)))
You can change the code as follows:
import hashlib
import itertools
abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#0123456789"
abc_list = list(abc)
combinations_object = all_combinations(abc_list)
def combo():
file_name = open("hashes.txt", "r")
for password in file_name:
password = password.strip()
for comb in combinations_object:
glue = "".join(comb)
hash_object = hashlib.md5(glue.encode())
md5_hash = hash_object.hexdigest()
if md5_hash == password :
print("Your password is: " + "'" + glue +"' "+ md5_hash)
break
When you use break, what you are saying is break the loop I'm currently in.
Notice that your condition is wrapped by three for loops, so it will only break the inner inner loop and keep going with the rest.
What you can do is what Jason Baker sugests in https://stackoverflow.com/a/438869/16627440.
Change that break to return md5_hash and call the function in your print.
if md5_hash == password :
return md5_hash
# Outside your function
print("Your password is: " + "'" + glue +"' "+ combo())

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.

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