I am trying to create a loop that compares strings from a list I have already created. The list is of passwords, and the same passwords hashed with md5. I have a function that does the hashing, and another that prints out the list of both passwords. The new function "findmd5" is supposed to compare each md5 encrypted value of the password list with the encrypted string that is passed in. "pass2check" is a predetermined string that I am trying to use in the loop, its md5 value should return the password "football". The code in my new function is very incomplete because I am lost on the next steps to take..
import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]
def makemd5(key_string):
new_key_string = key_string.encode('utf-8')
return (hashlib.md5 ( new_key_string ).hexdigest())
def createmd5list(passwordlist):
for passlist in passwordlist:
hashlist = makemd5(passlist)
print (passlist,",",hashlist)
def findmd5(pass2check):
for line in open(passwordlist + hashlist):
if pass2check in line:
print(True)
else:
print(False)
def main():
pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
main ()
you can try this ():
import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]
def listOfHashs():
return [hashlib.md5(item.encode('utf-8')).hexdigest() for item in passwordlist]
def main():
pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
index = listOfHashs().index(pass2check)
print(passwordlist[index] if index >= 0 else "Hash not found !")
main()
in this version i've tried to modify your code:
import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]
def makemd5(key_string):
new_key_string = key_string.encode('utf-8')
return (hashlib.md5 ( new_key_string ).hexdigest())
def createmd5list(passwordlist):
hashlist = []
for passlist in passwordlist:
hashlist += [makemd5(passlist)]
return hashlist
def findmd5(pass2check):
for index, line in enumerate(createmd5list(passwordlist)):
if pass2check in line:
return index
return -1
def main():
pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
index = findmd5(pass2check)
if index >= 0:
print passwordlist[index]
else:
print "Hash not found !"
main()
You do not need to create the list of hashed passwords. Instead, you build the digest and filter inside the list comprehension and the final list only contains the valid solutions.
Reworking your own code, it could look like
import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]
def findmd5(pass2check):
result = [password for password in passwordlist
if hashlib.md5(password).hexdigest() == pass2check
]
if len(result):
print("The answer is")
for password in result:
print(password)
else:
print("Password not found")
def main():
pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
findmd5(pass2check)
main ()
This will print all the valid solutions
Related
Basically im doing a project in python as part of my full stack course, and i have ran into wall.
My project is a parking lot system, which gets you a ticket with your cars number, unique code, time entered. At the exit you will have to write the unique code and it will calculate the cost for the parked time. I created a class named Key which creates the object it self with the exit time as None, but my trouble begins by trying to update the self.exit which doesn't work out for me using the the function exit_time. Every time a car enters the data is written to a file using pickle, i tried using a list to be able to edit the object but something isn't working out for me.
Also I tried many varieties by calling the function or what happens in the function it self.
THIS IS MY MAIN
list_of_cars = []
while True:
startmessage() # prints message
choice() # prints message
action = input("\nYour choice: ")
if action == "1":
choice_one() # prints message
car_number = input(" here: ")
new_client = Key(car_number)
list_of_cars.append(new_client)
writing_file(list_of_cars)
reading_file()
if action == "2":
choice_two() # prints message
exit_key = input(" here: ")
Key(exit_key).exit_time(exit_key)
READ AND WRITE
def reading_file():
with open("parking.data", "rb") as readfile:
list_of_cars = pickle.load(readfile)
print("testing", [str(x) for x in list_of_cars])
readfile.close()
return list_of_cars
def writing_file(list_of_cars):
with open("parking.data", "wb") as myfile:
pickle.dump(list_of_cars, myfile)
myfile.close()
return list_of_cars
THE CLASS
import random
import pickle
import datetime as dt
class Key:
def __init__(self, car_number):
self.car_number = car_number
self.key = self.generate()
self.enter = self.enter_time()
self.exit = None
"""
creates the key it self and while creating it checks if it already exists so that there will be no duplicates
"""
def generate(self):
key = ""
chunk = ""
alphabet = "ABCDEFGHIJKLMNOPQRZTUVWXYZ1234567890"
while True:
while len(key) < 8:
char = random.choice(alphabet)
key += char
chunk += char
if len(chunk) == 3:
key += "-"
chunk = ""
key = key[:-1]
with open("parking.data", "rb") as readfile:
new_list = pickle.load(readfile)
if key in new_list:
key = ""
else:
return key
def __str__(self):
return f"{self.car_number},{self.key}," \
f"{self.enter},{self.exit}"
def enter_time(self):
start = str(dt.datetime.now().strftime('%H:%M:%S'))
return start
def exit_time(self, exit_key):
from read_and_write import reading_file
list_of_cars = reading_file()
if exit_key in list_of_cars:
self.exit = str(dt.datetime.now().strftime('%H:%M:%S'))
print("IT WORKED!!!")
print("got to the function :/")
your conditional is:
if exit_key in list_of_cars:
exit_key is OM7-XVX
list_of_cars is ['5412,OM7-XVX,21:09:42,None1',...]
So...
'OM7-XVX' in ['5412,OM7-XVX,21:09:42,None1'] -> False
'OM7-XVX' in ['5412,OM7-XVX,21:09:42,None1'][0] -> True
Therefore replace the conditional with
if any(exit_key in v for v in list_of_cars):
So basically I'm trying to generate different caseIDs, but to avoid duplicates I'm trying to re-run the function if the case is already in the database.
Here's some code:
async def openuseless():
with open("caseids.json", "r") as f:
caseids = json.load(f)
return caseids
async def addcaseidtodb(caseid):
e = openuseless()
e[str(caseid)] = {}
with open("caseids.json", "w") as f:
json.dump(e, f)
return True
async def id_generator(size=10, chars=string.ascii_uppercase + string.digits):
x = ''.join(random.choice(chars) for _ in range(size))
existing = openuseless()
for caseid in existing:
if caseid == x:
# repeat function
print("e")
else:
await addcaseidtodb(x)
The questions is: How would I repeat the function from if caseid == x?
The general pattern for this is
def some_function():
while True:
# do things
if not repeat_condition:
break # or return or etc
You'll see this a lot for input validation.
def get_integer(prompt="Enter an integer: "):
while True:
user_input = input(prompt)
try:
result = int(user_input)
except ValueError:
print("Invalid input -- must be an integer")
return result
I'm using an online md5 generator to get the hash value of 'football'. When Python converts my input "football" at the prompt it generates a different hash. It then generates another totally different hash from the word "football" thats in my list. So no match when it compares them. I have hashed the word "football" in different online md5 generators and get the same result. Only in Python do i keep getting different results. Thanks for any help.
import hashlib
def dictionary_attack(password_hash):
dictionary = ['letmein', 'password', '12345', 'football']
password_found = None
for dictionary_value in dictionary:
temp_value = hashlib.md5('dictionary_value'.encode('utf-8'))
hashed_value = temp_value.hexdigest()
if hashed_value == password_hash:
password_found = True
recovered_password = dictionary_value
if password_found == True:
print(f'Found match for hashed value: {password_hash}')
print(f'Password recovered: {recovered_password}')
else:
print(f'password not found')
def main():
objhash = input('Enter value: ')
hashobj = hashlib.md5('objhash'.encode('utf-8'))
password_hash = hashobj.hexdigest()
dictionary_attack(password_hash)
if __name__ == '__main__':
main()
You're not computing the hash of "football". You're computing the hash of the string "dictionary_value".
Change the line
temp_value = hashlib.md5('dictionary_value'.encode('utf-8'))
in dictionary_attack to
temp_value = hashlib.md5(dictionary_value.encode('utf-8'))
Likewise, in main, change
hashobj = hashlib.md5('objhash'.encode('utf-8'))
to
hashobj = hashlib.md5(objhash.encode('utf-8'))
I was programming a project of secret messages which uses a few lists and appends. To my understanding, I don't think that any of my lists are out of range so I am very confused on why I am getting this error. Here is my code.
from tkinter import Tk, messagebox, simpledialog
def is_even(number):
return number % 2 == 0
def get_even_letters(message):
even_letters = []
for counter in range(0, len(message)):
if is_even(counter):
even_letters.append(message[counter])
return even_letters
def get_odd_letters(message):
odd_letters = []
for counter in range(0, len(message)):
if not is_even(counter):
odd_letters.append(message[counter])
return odd_letters
def swap_letters(message):
letter_list = []
if not is_even(len(message)):
message = message + 'x'
even_letters = get_even_letters(message)
odd_letters = get_odd_letters(message)
for counter in range(0, int(len(message)/2)):
letter_list.append(odd_letters[counter])
letter_list.append(even_letters[counter])
new_message = ''.join(letter_list)
return new_message
def get_task():
task = simpledialog.askstring('Task', 'Do you want to encrypt or decrypt?')
return task
def get_message():
message = simpledialog.askstring('Message', 'Enter the secret message: ')
return message
root = Tk()
root.withdraw()
while True:
task = get_task()
if task == 'encrypt':
message = get_message()
encrypted = swap_letters(message)
messagebox.showinfo('Ciphertext of the secret message: ', encrypted)
elif task == 'decrypt':
message = get_message()
decrypted = swap_letters(message)
messagebox.showinfo('Plaintext of the secret message: ', decrypted)
else:
break
root.mainloop()
Here is my error code:
Traceback (most recent call last):
File "C:/Users/Osprey/AppData/Local/Programs/Python/Python36-32/secret_messages.py", line 52, in
encrypted = swap_letters(message)
File "C:/Users/Osprey/AppData/Local/Programs/Python/Python36-32/secret_messages.py", line 31, in swap_letters
letter_list.append(odd_letters[counter])
IndexError: list index out of range
It seems you indented return of your functions earlier than you should.
In:
for counter in range(0, len(message)):
if not is_even(counter):
odd_letters.append(message[counter])
return odd_letters
The return odd_letters will activate after the append, when your if condition is met.
What that means is that, as soon as your function finds a number that isn't even, it will append to the odd_letters and will return a list with only that number, since you returned it too early. That's why you get an IndexError, your list only has one item, so it will only accept it in case you only query it for index 0.
To fix it, just remove 4 spaces. The other function has the same problem.
Alright so I was messing around with the code and when I did this:
def get_message():
message = simpledialog.askstring('Message', 'Enter the secret message: ')
return str(message)
it worked!!!
import sys
import pickle
import string
def Menu():
print ("***********MENU************")
print ("0. Quit")
print ("1. Read text file")
print ("2. Display counts")
print ("3. Display statistics of word lengths")
print ("4. Print statistics to file")
def readFile():
while True:
fileName = input("Please enter a file name: ")
if (fileName.lower().endswith(".txt")):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return fileName
THE_FILE = ""
myDictionary = 0
def showCounts(fileName):
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(fileName, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
print("Number count: " + str(numCount))
print("Comma count: " + str(commaCount))
print("Dot count: " + str(dotCount))
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
def showStats(fileName):
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(fileName, 'r') as f:
for line in f:
words = line.split()
for word in words:
temp2.append(word)
temp1.append(len(word))
for x in temp1:
if x not in lengths:
lengths.append(x)
lengths.sort()
dictionaryStats = {}
for x in lengths:
dictionaryStats[x] = []
for x in lengths:
for word in temp2:
if len(word) == x:
dictionaryStats[x].append(word)
for key in dictionaryStats:
print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))
return dictionaryStats
def printStats(aDictionary):
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
choice = -1
while choice !=0:
Menu()
choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
if choice == 0:
print ("Exit program. Thank you.")
sys.exit
elif choice == 1:
THE_FILE = readFile()
elif choice == 2:
showCounts(THE_FILE)
elif choice == 3:
showStats(THE_FILE)
elif choice == 4:
printStats(myDictionary)
else:
print ("Error.")
I'm trying to open a file, have it display the statistics of the word lengths, and then have it make a new file with the statistics of the word lengths. I can read the file and have it display the statistics, but when I print the statistics to file I get an error - "int" object is not iterable. Any ideas? Thanks guys!
Error:
Traceback (most recent call last):
File "hw4_ThomasConnor.py", line 111, in <module>
printStats(myDictionary)
File "hw4_ThomasConnor.py", line 92, in printStats
for key in aDictionary:
TypeError: 'int' object is not iterable
The problem is that you set myDictionary to 0 at the top of your program, and then are sending it to your file writing function here printStats(myDictionary).
In this function you have this line for key in aDictionary, and since you passed in 0, this is effectively for key in 0 which is where the error comes from.
You need to send the result of the showStats function to your printStats function.
As this is looking like homework, I will leave it at that for now.
Sorry I am confused. in the showStats function I have to somehow say
"send results to printStats function" and then in the printStats
function I have to call the results? How would I do that exactly?
The printStats function is expecting a dictionary to print. This dictionary is generated by the showStats function (in fact, it returns this dictionary).
So you need to send the result of the showStats function to the printStats function.
To save the return value of a method, you can assign it on the LHS (left hand side) of the call expression, like this:
>>> def foo(bar):
... return bar*2
...
>>> def print_results(result):
... print('The result was: {}'.format(result))
...
>>> result = foo(2) # Save the returned value
Since result is just like any other name in Python, you can pass it to any other function:
>>> print_results(result)
The result was: 4
If we don't want to store the result of the function, and just want to send it to another function, then we can use this syntax:
>>> print_results(foo(2))
The result was: 4
You need to do something similar in your main loop where you execute the functions.
Since the dictionary you want to print is returned by the showStats function, you must call the showStats function first before calling the printStats function. This poses a problem if your user selects 4 before selecting 3 - make sure you find out a work around for this. A simple work around would be to prompt the user to calculate the stats by selecting 3 before selecting 4. Try to think of another way to get around this problem.
Here:
THE_FILE = ""
myDictionary = 0
you set integer to myDictionary.
and later you do:
printStats(myDictionary)
and as you try to interate over keys of dictionary inside, you fail.