i know how to save a users input to a text file but how do i encrypt it? here is what i have for saving a users input to text file. i tried f.encrypt("Passwords_log.txt" but had no results
import time
password1 = input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
f.write(password)
f.write('\n')
f.close()
print("Done!")
There are some Python packages worth checking out that deal with cryptography.
Cryptography
PyCrypto
A simple example from cryptography would be the following:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
plain_text = cipher_suite.decrypt(cipher_text)
check out password hashing.
then i'd suggest you use https://pythonhosted.org/passlib/ or pycrypto; depending on what alorithm you choose.
this is just to store the encrypted password. to then encrypt data have a look at https://pypi.python.org/pypi/pycrypto/2.6.1.
I guess you want to get some sort of a hash for the password, but file objects have nothing to do with that. You may try to use base64 encoding (like here), or any other other algorithm of the kind.
Your code:
import time
import base64
password1 = raw_input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
password = base64.b64encode(password)
f.write(password)
f.write('\n')
f.close()
print("Done!")
You said, you tried base64 but it didn't work. Here is how you can make it work:
import base64
import time
password1 = input("Please type a password: ")
print("Your password has passed the verification!")
time.sleep(1)
print("Saving and encrypting password...")
time.sleep(2)
f=open("Passwords_log.txt",'a')
cr = base64.encodestring(password1)
f.write(cr)
f.write('\n')
f.close()
print("Done!")
This is not real encryption, I wouldn't recommend it for passwords, but since you said in your comment that you tried to use base64 and it didn't work, I thought I should show you how to use base64 in your code.
Related
I am trying to make a program that gets a password and a username using a tkinter entry, and then saves it on an external file. Here is what I have got so far:
def validateLogin(username, password):
filename = input("What is your first name?: ")
c = open(filename, "w");
print("username entered :", username.get())
print("password entered :", password.get())
c.write(username)
return
. That is just the part that I am having trouble with at the moment.
c.write(username) attempts to write an object of type StringVar, but files opened with c = open(filename, "w") only work with text, a.k.a. str.
To extract the string from a StringVar, use get, as you were using earlier in your code:
c.write(username.get())
c.close() # don't forget to close the file
I was trying to make some sort of login system,
I have it so that if a username and password are in test.txt (there is multiple ones) it should let you login, I haven't even passed the step of verifying if the username and password are in the txt file and its destroying me, I don't know how to do it and I tried for hours, I made it so "if you find this username in the text file, give me the line number and check if the password this password is in the same line of the username ,(I used split (',')) , if both email and password entered are existent in the txt file and in the same line then..(didn't do that yet).
so it is confusing me, lots of errors, if no errors then it isn't working like I intended, here is my spaghetti code
def test():
with open('test.txt', 'r') as f:
for num, line in enumerate(f,1):
username = line.split(',')
if username in num:
if username == q1:
print("found user in line: " + num)
Line = num
password = line.split(',')
if password in Line:
if password == q2:
print("found pass in line: " + num)
can someone help me fix this and explain to me how storing data in .txt files work and how to retrieve them? YouTube and google didn't help much really, if you can suggest a video that will be cool too, because I'm confused at this point, all I have left is to try MongoDB because it has functions to retrieve data and store it already built in
but as its local on my pc not on the internet, I don't think I will need MongoDB, so that will be an overkill for a local test
With json, you can get it done this way:
JSON File
{
"user1":{"password":"123456"},
"user2":{"password": "abcde"}
}
Python
import json
def test(username, password):
with open("answer.json", "r") as read_it:
data = json.load(read_it)
if data[username][password] == '123456':
print('User found!')
else:
print('User or password doesn\'t exist')
test('user1', 'password')
If you want to use a text file, then as a simple example:
cat test.txt
aklaver, dog
adrian, cat
alklaver, fish
user_name = 'aklaver'
with open('test.txt', 'r') as pwd_file:
lines = pwd_file.readlines()
for line in lines:
user, pwd = line.split(',')
if user == user_name:
print(pwd)
dog
I want to generate my Python code in a setup.exe. The user stores an email password in the script. My question: Do I have to additionally encrypt this password, even though I create an * .exe file.
def load_settings(self):
# print(__file__)
# print(os.path.dirname(__file__))
pf = os.path.dirname(__file__)
pa = os.path.join(pf, "settings.json")
# print(pa)
if os.path.exists(pa):
# print("Pfad existiert")
with open(pa, "r") as infile:
data = json.load(infile)
self.ein.pfadbez.setText(data["pfad"])
self.ein.name.setText(data["name"])
self.ein.mail.setText(data["mail"])
self.ein.ausgangserver.setText(data["smtp"])
self.ein.port.setText(data["port"])
self.ein.login.setText(data["login"])
self.ein.passwort.setText(data["pw"])
From the way you worded your question, it sounds like you want a user to store a password within the code itself, or in a text file. Variables are called variables because they vary - a password won't be saved between executions unless stored in plain text, which is where encryption will be needed.
Further, generating Python code from a Windows executable will still require that Python code to be put somewhere for execution, and since Python is fundamentally open-source, hiding it in a compiled package won't do much.
Going about text encryption is simple - since you're on Windows, you could use Pycryptodomex, which will simplify the process of encrypting text. This tutorial could help.
Here's my code:
from cryptography.fernet import Fernet
import pyperclip
print("For this program to work, please send the file named 'pwkey' and the encrypted code to the other user.")
key = Fernet.generate_key()
file = open('pwkey', 'wb')
file.write(key)
file.close()
print('File Generated')
original = input('Enter message>>>')
message = original.encode()
f = Fernet(key)
encrypted = f.encrypt(message)
encrypted = encrypted.decode("ascii")
print('Encrypted:', encrypted)
pyperclip.copy(encrypted)
print('Please tell the other user to input the encrypted code in the Decrypt program')
print('(Code copied to Clipboard)')
print("Note: Please delete the 'pwkey' file after sending it to the other user. It
is for one-time use only.")
And decrypting
# Decrypt
from cryptography.fernet import Fernet
print("For this program to work, make sure you have the file named 'pwkey' in your Python folder and the encrypted "
"code.")
file = open('pwkey', 'rb')
key = file.read()
file.close()
print('Key Retrieved')
encrypted = input('Please input your encrypted code>>>')
encrypted = bytes(encrypted, 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(encrypted)
decrypted = decrypted.decode()
print('Decrypted Message:')
print(decrypted)
print("Note: Please delete the 'pwkey' file after getting the decrypted message.")
I have been trying to work out how to look for matching words in a csv file, such a user account detail.
What I have already done is creating two csv files with a username in one and a password in the other, putting them into python and then create a script that lets the user log in, but I can't get it to search for just one username if there are more than one in the csv file.
Here is my code:
import csv
#imports and loads usernames and passwords
usernames = []
passwords = []
infile = open("usernames.csv",'r')
reader=csv.reader(infile)
for i in reader:
usernames.append(i)
infile.close()
infile = open("passwords.csv",'r')
reader=csv.reader(infile)
for i in reader:
passwords.append(i)
infile.close()
#the log in script
def login():
print("Please enter your username:")
userlogin=input()
print("Please enter your password:")
passlogin=input()
if userlogin in usernames and passlogin in passwords:
print("Welcome, " + userlogin)
else:
print("Sorry, that's not a valid login")
Thank you for any help given
I think there is a flaw in your approach.
You cannot combine any username with any password.
If you are going to use your code this way,
One password will become applicable for all.
Try to create a dictionary or some kind of mapping where a single password will be checked instead of all present passwords.
If you want to add them, I would suggest using a pandas dataframe which will give you structure and checking will be easier as well.
import pandas as pd
df = pd.DataFrame()
df['usernames'] = pd.read_csv('usernames.csv')
df['passwords'] = pd.read_csv('passwords.csv')
if df[(df['usernames'] == your_user_name) &
(df['passwords'] == your_password)].empty() is not True:
print("username and password present")
else:
print("username and password not present")
I'm a beginner in Python and ran across an error. I am trying to create a programme that will take a username and password made by a user, write them into lists and write those lists to files. Here is some of my code:
This is the part where the user is creating a username&password.
userName=input('Please enter a username')
password=input('Please enter a password')
password2=input('Please re-enter your password')
if password==password2:
print('Your passwords match.')
while password!=password2:
password2=input('Sorry. Your passwords did not match. Please try again')
if password==password2:
print('Your passwords match')
My code works fine up until this point, where I get the error:
invalid file: <_io.TextIOWrapper name='usernameList.txt' mode='wt' encoding='cp1252'>.
I'm not sure why this error is being returned.
if password==password2:
usernames=[]
usernameFile=open('usernameList.txt', 'wt')
with open(usernameFile, 'wb') as f:
pickle.dump(usernames,f)
userNames.append(userName)
usernameFile.close()
passwords=[]
passwordFile=open('passwordList.txt', 'wt')
with open(passwordFile, 'wb') as f:
pickle.dump(passwords,f)
passwords.append(password)
passwordFile.close()
Is there any way to fix the error, or another way to write the lists to a file?
Thanks
You had the right idea, but there were a number of issues. When the user passwords do not match, normally you would prompt for both again.
The with block is designed to open and close your files, so there is no need to add a close at the end.
The script below shows what I mean, you will then have two files holding a Python list. So trying to view it will not make much sense, you will now need to write the corresponding read part to your code.
import pickle
userName = input('Please enter a username: ')
while True:
password1 = input('Please enter a password: ')
password2 = input('Please re-enter your password: ')
if password1 == password2:
print('Your passwords match.')
break
else:
print('Sorry. Your passwords did not match. Please try again')
user_names = []
user_names.append(userName)
with open('usernameList.txt', 'wb') as f_username:
pickle.dump(user_names, f_username)
passwords = []
passwords.append(password1)
with open('passwordList.txt', 'wb') as f_password:
pickle.dump(passwords, f_password)
usernameFile=open('usernameList.txt', 'wt')
with open(usernameFile, 'wb') as f:
In the second line usernameFile is a file object. The first argument to open must be a file name (io.open() also supports file descriptor numbers as ints). open() tries to coerce its argument to a string.
In your case, this results in
str(usernameFile) == '<_io.TextIOWrapper name='usernameList.txt' mode='wt' encoding='cp1252'>'
which is not a valid filename.
Replace with
with open('usernameList.txt', 'wt') as f:
and get rid of usernameFile completely.