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.
Related
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'}
Sorry for the messy code. I didn't have time really. I'm new and just been experimenting. I just wanna know why the strings aren't replaced.
As you can see, the "b64ed" and "final_product" are the same...
Sorry in advance. I'm stupid xD
import base64;
import time;
import os;
import random;
import string;
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast
enc_method = input("Would you like to manually input the text or load a .txt file? \n Press 1 for manual or 2 for importing: \n");
if enc_method == "1":
filename = input("Enter the filename.txt: ");
print("Importing String.... \n")
with open(filename) as fn:
toEnc_string = fn.read();
print("String imported!");
print(toEnc_string)
elif enc_method == "2":
toEnc_string = input("Paste or Type the string you want to encrypt: \n");
else:
print("For fucks sake...")
def oneS():
return time.sleep(1)
def clearScreen():
print("Clearing screen in 5...")
time.sleep(1)
print("4...")
time.sleep(1)
print("3...")
time.sleep(1)
print("2...")
time.sleep(1)
os.system("clear")
clearScreen()
def randomString(lenOfThatshit):
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(lenOfThatshit))
def bs64e(x):
rummed = x.encode("utf-8")
encoded = base64.b64encode(rummed)
return encoded
print("You will now be asked to chose random Characters about 10 times. Choose differently each time.")
rs1 = input("Choose 6 random letters without spaces. Dont repeat: ")
rs2 = randomString(len(rs1))
#rs2 = input("Choose 6 more random letter without spaces. Dont repeat: ")
randStr = list(rs1)
randStr2 = list(rs2)
b64ed = str(bs64e(toEnc_string))
for i in range(6):
final_product = b64ed.replace(str(randStr[i]) , str(randStr2[i]))
print(str(randStr[i]) + "to " + str(randStr2[i]))
passes = open("the special random characters.txt", "w")
amount_written = passes.write(str(randStr) + "\n" + str(randStr2))
print(b64ed)
print("\n")
print(len(b64ed))
print("\n")
print(final_product)
print("\n")
print(len(final_product))
#print("Number of bytes written : " + str(amount_written))
passes.close()
Again, the code is really messy, I know. And there are many imports unused still. Forgive me. Also I will take any ideas.
You had a logical error there, always replacing chars in the b64ed string, so only the last of the replacement characters could actually be replaced. So you would see changes only if b64ed happened to contain the randStr[5] character, otherwise final_product would just be the exact same as b64ed.
Part of your code should look like this:
final_product = b64ed
for i in range(6):
final_product = final_product.replace(str(randStr[i]) , str(randStr2[i]))
print(str(randStr[i]) + " to " + str(randStr2[i]))
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)])
I have an assignment for my class, and even when I try everything, something seems to go wrong with my code. I'm supposed to make a tiny program that would check the strength of one's password. Could anyone tell me what I'm doing wrong? Much appreciated.
p = raw_input("Enter password") if len(p) <= 6:
print("Weak1") elif len(p) > 6 and len(p) <=12:
if p.lower:
print("Weak2")
elif p.upper() or int():
print("Medium4") elif len(p) > 12:
if p.lower and not p.upper():
print("Strong6")
elif p.upper() and p.lower():
print("Strong7")
elif int() and p.lower():
print("Strong9")
you have a lot of problems in your syntax. after reformatting your code,
consider these builtin methods. full list here
>>> password = "mylowercasepassword"
>>> password.islower()
True
>>> password2 = "MYSPRPSSWRD"
>>> password2.islower()
False
>>> password2.isupper()
True
>>> pwd = "MySvp3rStr0ngpw4"
>>> pwd.isalpha()
False
>>> pwd.isalnum()
True
Instead of using p.lower(), p.upper() and etc, which always will evaluate true, use the methods shown below.
You can rewrite your code such that, but try to understand more genuine solutions. Btw, I've fixed some parts of your code.
p = raw_input("Enter password")
if len(p) <=6:
# abCd1, Psw44 etc.
print "Your password is weak"
elif len(p) >6 and len(p)<=12:
## Password, pAssphrase etc.
if p.islower():
#password, passphrase
print "Length is ok, but you should use mixed case or whatever else"
elif p.isupper() or p.isdigit():
#PASSWORD, PASSPHRASE (is upper), 712356433 (is digit)
print "Another warning message"
#other elifs and else
elif len(p)>12:
#l0ngPasswordjumped0v3r1azyrabbit
if p.isalpha() or p.isalnum():
#myReallyLongPassword (is alpha), l0ngPasswordjumped0v3r1azyrabbit (is alnum)
print "Really strong"
elif (not p.islower()) and (not p.isuppper()) and (not p.isdigit()):
#ParaPsychOlOGY (is not lower, is not upper, and is not digit)
print "Another strong"
#other elifs and else
#other conditional
What you are doing wrong is that you are inventing your own password strength estimator which is not based on the best principles and research, but your own invented rules :)
There exist a Python library zxcvbn, which gives more realistic password strength estimations.
Please note that this is probably not answer what you want, but the answer what you would do if you would be building a real, secure, service.
You need to use re module to find if String contains both uppercase and lowercase, How many uppercase and lowercase, etc..
Here is a simple implementation I did.
It's still a Fool script! But still works!
import sys, os
try:
import re
except:
os.system("python -m pip install re")
import re
try :
import string
except:
os.system("python -m pip install string")
import string
password = (raw_input("Type the Password : "))
p = password
strength = []
def AnalyzePassword():
total = 0
for k in strength:
total = total + int(k)
total_analyze = int(total) + 0.0
analyzed = int( (total_analyze) * 10)
analyzed = str(analyzed).replace("00", "0")
result = analyzed
return result
def PassLvlChecker(passd):
if len(passd) < 18: strength.append("-4")
elif len(passd) > 18: strength.append("4")
if passd.isalpha(): strength.append("2")
if bool(re.compile('[\W]+').findall(passd)) is True: strength.append("7")
if bool(re.compile("[A-Z]+").findall(passd)) is True: strength.append("5")
if bool(re.compile("[0-9]+").findall(passd)) is True: strength.append("9")
if len(passd) > 18 and \
bool(re.compile('[\W]+').findall(passd)) is True and\
bool(re.compile("[A-Z]+").findall(passd)) is True and\
bool(re.compile("[0-9]+").findall(passd)) is True:
strength.append("15")
strength.append(str(len(passd)))
return AnalyzePassword()
def checkAgain(pas):
if pas == '':
p = raw_input("Type the Password : ")
checkAgain(p)
else:
passStrength = PassLvlChecker(password)
print "Your password is", str((int(passStrength))) + "%", "Secured!"
if p == '':
p = (raw_input("Type the Password : "))
checkAgain(p)
else:
passStrength = PassLvlChecker(password)
print "Your password is", str((int(passStrength))) + "%", "Secured!"
I have been creating a program and I want it to check when a password is weak, medium or strong. I have defined each one of the uppercase, lowercase and digits so the program can check if the pass's strength. I have set it so a+b+c (all flags) is strong etc. but when I enter 7 characters, all lowercase it just restarts my program. I need it to tell me the password is weak etc. If anyone could give me any hints I would be grateful! Thanks!
import sys
import os
def checkPass():
passLoop = True
while passLoop:
print("Welcome user!")
x = len(input("Please enter your password, between 6 and 12 characters. "))#Asks for age
if x <= 6 or x >= 12:
print("Your password is the wrong length.")
r = input("Please press any key to restart the program")
passLoop = False
checkPass()
###########################
def upperCase(x):
for char in x:
if char.isupper():
return(1)
return(0)
###########################
def lowerCase(x):
for char in x:
if char.islower():
return(1)
return(0)
###########################
def digitFlag(x):
for char in x:
if char.isalnum():
return(1)
return(0)
###########################
def passStrength():
a = upperCase
b = lowerCase
c = digitFlag
totalValue = a + b + c
if totalValue == a or b or c:
print("Your password is weak, please re-enter it!")
if totalValue == a and b or a and c or b and c:
print("Your password is medium, please re-enter it!")
if totalValue == a and b and c:
print("Your password is strong, please re-enter it!")
passStrength()
You didn't mention any stack trace or exceptions being thrown in your description, but I think that is what is happening to you. The problem is your use of input(). Change that to raw_input() and you should start to get the functionality you expect.
Have you ever heard of iPython? It is just a python shell environment, but it might be a utility that would have helped you more clearly see what was happening (noticing and even post-mortem debugging your application).
Let me know if that does not clear things up for you.
Your problem is with that passLoop = False is never reached
Try this:
def checkPass():
passLoop = True
while passLoop:
print("Welcome user!")
x = len(input("Please enter your password, between 6 and 12 characters. "))#Asks for age
if x <= 6 or x >= 12:
print("Your password is the wrong length.")
r = input("Please press any key to restart the program")
else:
passLoop = False