Generate a password from SHA3-512 hash value - python

I'm new to python, currently taking an IT as a master's degree. I'm working on decoding a password from a hash value.
This is how I'm currently set up. I know it's wrong and any help would be greatly appreciated.
import itertools
import time
from Crypto.Hash import SHA3_512
# Function to brute force the password
def tryPassword(passwordSet):
start = time.time()
# Allowed characters in the password
chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!##$%^&*()_-+=[{]}|:;'\",<.>/?"
attempts = 0
for value in range(1, 9):
# Build up a string to test against, character by character
for letter in itertools.product(chars, repeat=value):
attempts += 1
letter = ''.join(letter)
hash_object = SHA3_512.new()
hash_object.update((letter).encode("utf-8"))
tmp_hash = hash_object.hexdigest()
print(tmp_hash)
#if the string we are building matches the password given to us, return from the function
if tmp_hash == passwordSet:
end = time.time()
distance = end - start
return (attempts, distance)
password = input("Password >")
tries, timeAmount, = tryPassword(password)
print("The password %s was cracked in %s tries and %s seconds!" % (password, tries, timeAmount))

Since the purpose is to crack a hashed password, that's what should be the parameter to the function, not a plain-text password.
Then in the loop it needs to hash each candidate password, and compare the hash to the input.
import itertools
import time
from Crypto.Hash import SHA3_512
def hash_password(password):
hash_object = SHA3_512.new()
hash_object.update(password.encode("utf-8"))
return hash_object.hexdigest()
def tryPassword(hashed_pass):
start = time.time()
# Allowed characters in the password
chars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`~!##$%^&*()_-+=[{]}|:;'\",<.>/?"
attempts = 0
for value in range(1, 9):
# Build up a string to test against, character by character
for letter in itertools.product(chars, repeat=value):
attempts += 1
candidate = ''.join(letter)
#if the string we are building matches the password given to us, return from the function
if hash_password(candidate) == hashed_pass:
end = time.time()
distance = end - start
return (attempts, distance, password)
password = input("Password > ")
tmp_hash = hash_password(password)
tries, timeAmount, found_password = tryPassword(tmp_hash)
print("The password %s was cracked in %s tries and %s seconds!" % (found_password, tries, timeAmount))

Related

Can I/How to jump back to a specific line of code using while & if-else together?

I've written my code to work fine, but if the user chooses to try a different output, I'd like to skip the introductory message. For example, if the user chooses to generate a different password, I'd prefer to return to line 11 (the request to enter a length requirement) rather than line 8. (which welcomes the user to the program).
import random
import string
import sys
another = True
while another:
8 print("Welcome to the Password Generator!")
# ask user for password length requirement
11 length = int(input("How many characters does your password require?: "))
# initialize character types
lower = string.ascii_lowercase
capitalize = string.ascii_uppercase
nums = string.digits
symbols = string.punctuation
# combine all char types
combine = lower + capitalize + nums + symbols
# randomize character types and add length requirement
randomization = random.sample(combine, length)
# construct the secure password
secure_pw = "".join(randomization)
# display password
print(secure_pw)
another = input("Would you like to generate a different secure password?: ")
while True:
if another == 'yes':
generate = True
break
elif another == 'no':
generate = False
sys.exit()
else:
another = input('Invalid response! Enter "yes" to continue or "no" to exit: ')

Password generator generates the same passwords

I'm trying to make a password generator in Python but I have some problems with it.
My code is down below:
import random
import time
f = open("password_list.txt", "a+")
start = time.time()
password = ""
chars= "123456789"
number = int(input("Number of passwords to generate? = "))
length = int(input("Password length? = "))
for p in range(number):
password = ""
for c in range(length):
password += random.choice(chars)
print(password)
f.write(password + "\n")
print('time: ' + str((time.time() - start)) + ' sec')
f.close()
Everything works fine but the only problem is sometimes it generates the same passwords in the text file. How can I avoid that?
One way to avoid the duplication issue is to put the passwords into a set in your loop, and keep looping until the length of the set is the number of passwords you want to generate. Then you can write the contents of the set to the file. This shows how to generate the set of passwords:
import random
chars= "123456789"
number = 5
length = 8
passwords = set()
while len(passwords) < number:
password = ""
for c in range(length):
password += random.choice(chars)
passwords.add(password)
print(passwords)
Sample output:
{'67824479', '67159221', '78423732', '77922952', '83499619'}

How can i not repeat a guess?

how can i brute force a password without repeating guesses, also without importing anything else? this is my code so far
import random
import string
guessAttempts = 0
myPassword = input("Enter a password for the computer to try and guess: ")
passwordLength = len(myPassword)
while True:
guessAttempts = guessAttempts + 1
passwordGuess = ''.join([random.choice(string.ascii_letters + string.digits)for n in range(passwordLength)])
if passwordGuess == myPassword:
print(passwordGuess)
print("Password guessed successfully!")
print("It took the computer %s guesses to guess your password." % (guessAttempts))
break
any help would be appreciated
Take the n-way product of string.ascii_letters + string.digits and iterate over it.
from itertools import product
passwords = map(''.join, product(string.ascii_letters + string.digits, repeat=n))
for (guessAttempts, passwordGuess) in enumerate(passwords, start=1):
...
itertools is in the standard library, so it's already installed whether you choose to use it or not: you may as well use it.

Repetitive Password code

I am trying to create a password generator. I have succeeded in creating a functional code but it keeps on showing how it generates the passwords instead of just giving three lines as shown:
This is my code:
def Generate(): #menu function, Generates a password
global password
print("Generating...")
chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!##$%^&*()?" #These are the avaliable characters available to the password
length = input("password length?") #asks for how long the user wants their password
if int(length) < 25: #Doesn't allow the code to print over 26 characters
length = int(length)
for p in range(3):
password = " "
for c in range(length): #for loop which
password += random.choice(chars) #randomly choses characters at random to create the password
print(password)
else:
print ("The password can only be between 8-24 characterss long")
Generate ()
This is my program running:
Generating...
password length?14
*
*C
*CD
*CDb
*CDbF
*CDbFA
*CDbFAi
*CDbFAiK
*CDbFAiKk
*CDbFAiKkA
*CDbFAiKkAa
*CDbFAiKkAa9
*CDbFAiKkAa9m
*CDbFAiKkAa9mr
7
7Y
7Ys
7Ysy
7Ysyj
7Ysyjj
7Ysyjj2
7Ysyjj28
7Ysyjj28C
7Ysyjj28Ch
7Ysyjj28Chq
7Ysyjj28Chqk
7Ysyjj28Chqk(
7Ysyjj28Chqk(k
E
E%
E%C
E%C8
E%C8(
E%C8(w
E%C8(w7
E%C8(w7M
E%C8(w7Mj
E%C8(w7MjP
E%C8(w7MjPO
E%C8(w7MjPOz
E%C8(w7MjPOzx
E%C8(w7MjPOzxx
Could you please help me to make the code just output three words?
Much appreciated.
You have indented this incorrectly:
for p in range(3):
password = " "
for c in range(length):#for loop which
password += random.choice(chars)#randomly choses characters at random to create the password
print(password)
It should be this:
for p in range(3):
password = " "
for c in range(length):#for loop which
password += random.choice(chars)#randomly choses characters at random to create the password
print(password)
By placing the print statement in the first loop, it will only execute at the end of each iteration of p, rather than each iteration of c.
There is so much things we could help you out here than just what you asked for actually! I'll write same code with your requirements ( assuming I got them all right ) with comments.
import random
def generate_password(): #menu function, Generates a password
# global password # NOT NEEDED BUT I"M ASSUMING THINGS HERE
print("Generating...")
chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!##$%^&*()?"#These are the avaliable characters available to the password
length = int(input("password length?")) #asks for how long the user wants their password
if length <= 26: #Doesn't allow the code to print over 26 characters -> THIS SHOULD BE LESS THAN OR EQUAL TO 26 BC YOU SAID OVER 26 CHARS
for p in range(3):
password = " " # EMPTY STRING.. PYTHON WOULDN'T MIND
for c in range(length): #for loop which
password += random.choice(chars) #randomly choses characters at random to create the password -> CONCATENATION HERE.. WE LOVE IT.
print(password) # THIS WAS OUT OF PLACE.
else:
print ("The password can only be between 8-24 characterss long")
generate_password () # PERFECT!
generate_password()
Now after I come with somewhat ok-ish code I can't sleep at night bc I know I can improve it even more if I do it in my way.
import random
import string
def generate_password(): #menu function, Generates a password
print("Generating...")
try:
length = int(input("password length?")) #asks for how long the user wants their password
if 8 <= length < 25: # Doesn't allow the code to print over 26 characters -> THIS SHOULD BE LESS THAN OR EQUAL TO 26 BC YOU SAID OVER 26 CHARS
password = ''.join(random.choice(string.ascii_letters + string.digits + "!##$%^&*()?") for _ in range(length)) # throw away variable caution here!
print(password)
else:
print("The password can only be between 8-24 characterss long")
generate_password() # PERFECT!
except Exception as e: # Do some homework on what kind of exception(s) you would like to catch ( like ValueError)
print(e)
pass # Don't just pass it. Do something here depending on the Exception
generate_password()
The print statement in your inner loop for the character selection, is the culprit here, just push it one indentation to the left and it should work.
for c in range(length): #for loop which
password += random.choice(chars) #randomly choses characters at random to create the password
print(password)
just keep it in the for p in range(3): loop.
Sure, just move print out of loop:
for c in range(length):
password += random.choice(chars)
print(password)
Also you could consider this:
password = ''.join([random.choise(chars) for _ in range(length)])

Compare Strings Loop Python

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

Categories

Resources