Password generator generates the same passwords - python

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'}

Related

Generate a password from SHA3-512 hash value

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))

How can I fix python printing unnecessary "in range" information

I want to make a advanced password generator. And I want to add a feature where each password is saved in a text file. But at the last part where it generates another password, Python prints each character step by step this causes to save each character! My computer crashed 3 times today because of this bug. Sorry for all the bad grammar or bad explanation.
Anyways here is my code:
import random
Alphabet = "abcdefghilmnopqrstuvwxyzABCDEFGHILMNOPQRSTUVWXYZ123456789()]\%$*#!><?"
FileAlphabet = "abcdefghilmnopqrstuvwxyz"
number = input("Number of passwords? ")
number = int(number)
length = input("Password length? ")
length = int(length)
for p in range(number):
password = ''
for c in range(length):
password += random.choice(Alphabet)
print(password)
text = password
saveFile = open("MOST_RECENT_PASSWORD.txt", 'w')
saveFile.write(text)
saveFile.close()
new = input("Generate another password? yes/no" )
FileName = ''
if new == "yes":
for pwd in range(number):
password = ''
for c in range(length):
password += random.choice(Alphabet)
FileName += random.choice(FileAlphabet)
password += random.choice(Alphabet)
print(password)
saveFile = open(FileName + ".txt", 'w')
saveFile.write(text)
saveFile.close()
Your last 2 for loops.
especially the
for c in range(length):
password += random.choice(Alphabet)
FileName += random.choice(FileAlphabet)
password += random.choice(Alphabet)
print(password)
saveFile = open(FileName + ".txt", 'w')
saveFile.write(text)
saveFile.close()
you're saying that for every character of your password it should:
increment the password by some random letter
And change the filename to a random letter
then increment the password again with some random letter
//printing the password is kinda ok allthough it only prints 2 characters
and then you save the 2 characters in ONE file
and redo every time
The bold parts are where the problems lie.
You have to move FileName += random.choice(FileAlphabet)
to the left, so under for c in range(length):
then also move
saveFile = open(FileName + ".txt", 'w')
saveFile.write(text)
saveFile.close()
to the left so it doesn't loop it.
For you the solution should be
for pwd in range(number):
password = ''
for c in range(length):
password += random.choice(Alphabet)
password += random.choice(Alphabet)
print(password)
FileName += random.choice(FileAlphabet)
saveFile = open(FileName + ".txt", 'w')
saveFile.write(text)
saveFile.close(
)

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.

When writing to a text document it doesn't give all of the passwords given

I made a Password Generator which gives me passwords by the quantity and length requested, I wanted to make all of the given passwords be saved into a txt document called "Your_Saved_Keys" however only one of the generated passwords are saved not all of them
import random
import time
print('''
Password Generator V2.0
=======================
''')
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#£$%^&*().,?
0123456789'
number = input('number of passwords? ')
number = int(number)
length = input('password length? ')
length = int(length)
print('''\nhere are your passwords: ''')
for pwd in range(number):
password = ''''''
for c in range(length):
password += random.choice(chars)
print(password)
save = input("""Do you want to save it to a txt file? Y/N""")
if save == "Y":
format = ".txt"
title = "Your_Saved_Keys"
text_file = open(title + format, "w")
text_file.write(password))
print("Save Successful")
if save == "N":
print("You Selected No")
print("-----------------------------------")
input("Press enter to exit")
Your password variable is being overwritten every time. Only the last password is available in it. You could just save all passwords to a list and then write it to the file. This code is working
import random
import time
print('''
Password Generator V2.0
=======================
''')
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#£$%^&*().,?0123456789'
number = input('number of passwords? ')
number = int(number)
length = input('password length? ')
length = int(length)
passwords=[]
print('''\nhere are your passwords: ''')
for pwd in range(number):
password=""
for c in range(length):
password+=random.choice(chars)
passwords.append(password)
print(password)
save = input("""Do you want to save it to a txt file? Y/N""")
if save == "Y":
format = ".txt"
title = "Your_Saved_Keys"
with open(title + format, "w") as text_file:
for password in passwords:
text_file.write(password+'\n')
print("Save Successful")
if save == "N":
print("You Selected No")
print("-----------------------------------")
input("Press enter to exit")
You ask for saving and also do the saving after the whole loop over range(number) is already done. So of course only the last generated password is saved.
Ask before the loop and save every password within the loop or save all passwords in a list and save the list afterwards.
You're writing password variable into file. password variable in your code stores the last generated password in the loop.
So, to achieve what you want,
Store your generated passwords in a list. (In the first loop, add each generated password in this list)
Then write the content of this list into your file.
Note: I suggest you to apply encryption to your file

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)])

Categories

Resources