If statement skips first condition. Trying to follow 1-4 Steps - if-statement

I am trying to make a virtual voting booth that accepts the user id encrypts it, verifies and validates voter id, then checks if the voter has already voted. But it skips the first condition. I'm not an expert programmer. I'm new and just learning python. I need your help! Thank you in advance for your expertise!
These are the steps:
Step 1: Voter generates a pair of private and public keys – for the purpose of digital signature. Voter uses his private key to sign his request and the public key of the CLA to send his/her message. The message must include the voter’s signed id, say, SSN (request) and the voter’s public key. The public keys of the CLA and CTF may be passed to a voter when he/she starts the session.
Step 2: CLA reads the message sent on Step 1 using its private key and, using the voter’ public key, finds the voter’s id . CLA encrypts the validation number using its private key and sends it to the voter. The voter finds the validation number, using the public key of the CLA.
Step 3: The CLA sends the list of validation numbers to the CTF using a symmetric key negotiated between CLA and CTF.
Step 4: The message from the user to the CTF must be encrypted using the public key of CTF.
The result show this:
C:\Python27\python.exe "C:/Python Projects/Virtual Election Booth/VEB.py"
Welcome to the Vitrual Election Booth.
Enter your voter id:1234
You have already voted! Thank you!
Process finished with exit code 0
Here is the code below:
from collections import Counter
import random
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto import Random
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
pubkey = key.publickey() # pub key export for exchange
vote_id = raw_input( '''\nWelcome to the Vitrual Election Booth.\n
Enter your voter id:''')#input from user
hash = SHA256.new(vote_id).digest() #creates vote id hash
encdata = pubkey.encrypt(vote_id, 32) #creates encrypted pubkey of hash
signature = key.sign(hash, pubkey)#signs the id and pubkey
assert pubkey.verify(hash, signature)
assert not pubkey.verify(hash[:-1], signature)
m = random.randint(4, 1000)
rand_val_num = random.randint(1, m)
encdata_2 = pubkey.encrypt(rand_val_num, 32)
file = open('cla.txt', 'w') #opens cla file (as a server)
file.write(str(encdata))#writes to cla file (saved vote_id hash to server)
decrypt_id = key.decrypt(encdata)
file.write(decrypt_id)
file.write(str(encdata_2))
file.close() #closes file
file = open('cla.txt', 'r')
verify_vote = file.read()#assign verify_vote to read file
if decrypt_id == verify_vote:
print '\n'
print 'Your voter id is verified!'
print '\n'
Vote = raw_input('Please place your vote: ')
file = open('ctf.txt', 'a') #open cla file (as a server)
file.write(str(publickey)) #writes publickey to cla file
file.write('\n')
file.write(Vote)
file.write('\n')
file.close() #closes file
else:
print('\n')
print 'You have already voted! Thank you!'
print '\n'

From looking at the code it looks like you are comparing decrypt_id with all the content in the file which contains more than just the decrypt_id data. Thus the if statement will never be executed as the data is not the same.

When you file.read(), you read the entire contents of the file, which you previously wrote with str(encdata), decrpyt_id, and str(encdata_2). For the sake of explanation, let's say encdata is 1, decrypt_id is 2, and encdata_2 is 3. verify_vote would be a string containing "123" - since that's what you wrote - and decrypt_id would be a string containing "2". The only case in which that if statement would evaluate to true is if both encdata and encdata_2 were empty strings.
Edit: Taking a longer look at this code, it looks like the purpose of the if statement is to prevent users from voting multiple times. What you might want to consider doing is creating a list of decrypt_ids which you add to each time a voter's id is verified and then make the if statement if decrypt_id not in verified_list:
So, the if block would become
if decrypt_id not in verified_list:
print '\n'
print 'Your voter id is verified!'
print '\n'
Vote = raw_input('Please place your vote: ')
file = open('ctf.txt', 'a') #open cla file (as a server)
file.write(str(publickey)) #writes publickey to cla file
file.write('\n')
file.write(Vote)
verified_list.append(decrypt_id)
else:
print '\n'
print 'You have already voted! Thank you!;
print '\n'
Another thing to note is that you open cla.txt for reading but never close it. You should place a file.close() after verify_vote = file.read().

Related

How to send the same word to each number using Twilio. I am importing random word from a text file to send to recipients

I am wanting to send the same random word from my text file to each recipient. Right now it sends a different random word to each phone number and I need it to be the same to all. I am using Twilio to send texts to numbers. Here is what I have tried below:
import os
from twilio.rest import Client
import random
# Open the file in read mode
with open("5words.txt", "r") as file:
allText = file.read()
word = list(map(str, allText.split()))
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
family = {'+123456789', '+123456789','123456789','123456789','123456987','123456789'}
for number in family:
client.messages.create(
body=('Your word of the day is ' + random.choice(word)),
from_='+12345678',
to=(number)
)
Set random.choice(word) to a variable before entering the for loop and use that variable name in the body of the text when calling the Twilio API.

Cannot create a reusable login on python

I am attempting to create a login system for a quiz program but am unable to get the outcome I want. The first function creates a file for the user so that I can later save their details onto it - however this is not the part I'm struggling with and is only there for reference. The bit that I cannot get to work is in the second function where I see if the 1st line of the users file is equal to the string that they have inputted(the password) as it always tells me that they are not equal so the program does not let the user save data onto their created file because the passwords do not match. Please could you tell me how I can fix this issue.
def create_login():
YorN = "nothing"
while YorN != "y":
name = raw_input(str("please input full name:"))
age = raw_input(str("please input age:"))
username = name[0:3] + age
password = raw_input(str("please enter password:"))
print "Are you sure you want to proceed with the username and password you have selected?"
YorN = (raw_input("Please select Y or N:")).lower()
f = open(username +".txt","w+")
f.write(password)
f.write("\n")
f.write(name)
f.write("\n")
f.write(age)
f.write("\n")
f.write(username)
f.write("\n")
f.close()
def login():
inp_username = raw_input(str("Please input your username:"))
inp_password = raw_input(str("Please input your password:"))
t = open(inp_username +".txt","r")
lines = t.readlines()
g = lines[0]
if inp_password == g:
print "Access Granted!"
else:
print "incorrect password"
login_or_create()
The problem:
Each line in a text file ends in a newline character. When you read in a line or lines, each of them still has that newline character attached.
But, your passwords do not end in newline characters do not match:
password => 'mypassword'
line_read_in_from_file => 'mypassword\n'
Solution:
strip() off the newline characters prior to doing the comparison, using the .strip() function that is associated with Python strings...
def login():
inp_username = raw_input(str("Please input your username:"))
inp_password = raw_input(str("Please input your password:"))
t = open(inp_username +".txt","r")
lines = t.readlines()
# lines[0] is a string and as a string, has a function called .strip()
g = lines[0].strip()
if inp_password == g:
print "Access Granted!"
else:
print "incorrect password"
login_or_create()
Strip the \n from lines[0] and make sure you are telling the username to your users i.e name[0:3]+age is the username.

Python - Text does not appear in code-triggered email sent if string is result of a formula

I am attempting to write a program that sends an email from Gmail, with a body of text that includes real time stock quotes. I am using a module to get stock quotes in string format (this works), and I wrote a function to send an email from gmail. The message_send function is only working if I give it a simple string. It is not working if I pass it the aapl_string variable. See code below:
from yahoo_finance import *
import smtplib
def message_send(messagebody):
fromaddr = 'REDACTED'
toaddrs = 'REDACTED'
msg = messagebody
# Credentials (if needed)
username = 'REDACTED'
password = 'REDACTED'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
aapl = Share('AAPL')
aapl.refresh()
price_aapl = aapl.get_price()
aapl_string = "The current price of AAPL is: " + price_aapl
print(aapl_string)
message_send(aapl_string)
Any ideas why the email sends, but contains blank text when using aapl_string as the argument for the message_send function?
Thanks!
You could do
message_send("The current value is %s" %price_aapl)
and that should make it work :)
I'm assuming price_aapl is an integer, and if that's the case then that is your whole problem. This is due to the inability of being able to add integers to strings so what you could do is use a format string.
ex:
aapl_string = "The current price of AAPL is: %d" % price_aapl
the %d is a placeholder for the integer price_aapl.
You can look here -> http://www.diveintopython.net/native_data_types/formatting_strings.html
for more information on formatting strings in python.

How to compare username entered by the user to the password stored in the file?

I am trying to make a bank which stores the username and password entered by the user in a file (text file).Now when , the user logs in he enters his username.Now how do i compare whether this username entered by the user is the same as the stored password when he/she created the account (stored in passw.txt).
Here is my code,
store_user=open("user.txt","a")
store_passw=open("passw.txt","a")
print "Type 1 to create a new acc or 2 to log in"
a=input("Your choice: ")
if a==1:
a=raw_input("Enter your username: ")
store_user.write(a+'\n')
store_user.close()
b=raw_input("Enter pass: ")
store_passw.write(b+'\n')
store_passw.close()
elif a==2:
a=raw_input("Enter username: ")
'''
Now how do I comapare the username entered by the user with my file user.txt
And also it should check the same userame has same associated password with passw.txt
'''
I would also like to know is this method easier or shall i store username and password in a dictionary and then append it in a file.If i do so , then how would i get the the username and password out of it? (Like a user enters his username , now how does my program go to the file where is username and password is stored and check if the username (key) matches to the password (value).
You need a structure. For instance you can use row number to get pair - user-password. That brings more problems then you can expect. Please use structure, and keep your data consistent. For instance you can put them into single file - reading whole record - name, password - goes always as single pice. There are simple ways - like comma separated values - python has csv module - https://docs.python.org/2/library/csv.html . Or you can go for something more complicated - JSON, XML - here is link for json: https://docs.python.org/2/library/json.html
I personally would not store in 2 files, but use a delimiter between elements and an other delimiter between values for that element
Example "Test1,pass1\nTest2,pass2" would be delimiter "\n" and ","
for your code you will have to find the linecount in file 1 then skip to that line in the other file to compare the passwords:
psudocode
open username
linefound = -1
for line,lineid in file
if line == user
linefound = lineid
close username
if linefound >= 0
open password
for line, lineid in file
if lineid == linefound
//compare do rest

user authentication script to run program using python

i am new on python and just started learning, i want to create a simple script to run a program by authenticating user, valid or not...
main problem, i am facing is that i have a file "users" in which i mentioned all valid users,
so i need a program which searches the input given by user in "users" file, if found then continue otherwise "authentication failed"
what i tried is ...
fp = open("users", "r")
for line in fp.readlines():
if "michel" in line : # user michel is available in users file
print "true"
else :
print "false"
it works, prints 'true' because michel is in file.. but in case of when user enters "mic" .. also prints true ...... so what will be the solution...
For starters, it is probably best for security purposes to use os.getlogin() to determine the user's login name rather than prompting the user to type their username. This will at least guarantee that the user logged in via some authentication mechanism to get onto the system, meaning that they have a known & consistent username.
So if you wanted to turn this into a function you could write:
def is_valid_user(username):
fp = open("users", "r")
for line in fp.readlines():
if username in line:
fp.close()
return True
fp.close()
return False
You could then call the function using:
import os
is_valid = is_valid_user(os.getlogin())
if is_valid:
print("valid user")
else:
print("invalid user")
Some suggestions for added security now and in the future:
Modify your "users" file to contain names surrounded by delimiters such as ":jonesj:" rather than "jonesj" and search for ":" + username + ":" in line which will avoid false positives in situations where a user "jones" is currently logged in and a username "jonesj" is in your "users" file but "jones" is not, and you incorrectly identify "jones" as being an authorized user (since "jones" is a subset of the string "jonesj").
Make sure the permissions on your "users" file is set to read-only so that users can't go add their username to the file to grant permissions to themselves.
Sometime in the future you may want to consider using LDAP or Kerberos server or some other more formal authentication mechanism rather than a "users" file. There are good python client libraries for quite a number of authentication backend servers.
You can use re to make sure the whole line is a match:
import re
fp = open("users", "r")
for line in fp.readlines():
if re.match('^michel$', line, re.I):
print "true"
else :
print "false"