Password strenght - python

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!"

Related

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.

Integer Validation Python

I need to add a validation whilst in a while loop.
However when I use this validation it doesn't work and instead only comes up with the error message saying I haven't used a base 10/an integer when I want it to come up with the validation error message and let the user try again.
I don't know if having it in a while loop makes the validation I use any different, does it?
Also do I need to change this "def inputNumber(message):" to what my input is stored as?
And this "userInput = int(input(message))" to what my input is stored as?
import time
import random
question = 0
score = 0
name = input("What is your full name?")
print ("Hello " + name, "welcome to The Arithmetic Quiz. Use integers to enter the answer!")
time.sleep(2)
operands1 = list(range(2, 12))
operators = ["+","-","x"]
operands2 = list(range(2, 12))
while question < 10:
operand1 = random.choice(operands1)
operand2 = random.choice(operands2)
operator = random.choice(operators)
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break
user_answer =int(input('{} {} {} = '.format(operand1, operator, operand2)))
I doubt you want to have your function definitions within a while loop like you're doing here:
while question < 10:
...
def inputNumber(message):
...
Instead, you can define the function outside the loop and call it x number of times from a loop elsewhere. E.g.
def inputNumber(message):
...
return userInput
while question < 10:
# pick random numbers/operators
...
# call inputNumber() with numbers/operators as message. Return user_answer
user_answer = int(inputNumber('{} {} {} = '.format(operand1, operator, operand2)))
# check if the answer is correct
...
# increment question so it doesn't run infinitely
question += 1
#user6104134 has already solved this problem; however, I'd like to provide an answer for anyone else having similar issues.
Try this solution
import random
import time
question = 0
score = 0
def inputnumber(prompt):
while True:
response = raw_input(prompt)
try:
if isinstance(response, int):
return int(response)
else:
print "Not an integer! Try again."
except ValueError:
print "Not an integer! Try again."
name = raw_input("What is your full name? ")
print ("Hello " + name, "welcome to The Arithmetic Quiz. Use integers to enter the answer!")
time.sleep(2)
operands1 = list(range(2, 12))
operators = ["+", "-", "x"]
operands2 = list(range(2, 12))
while question < 10:
operand1 = random.choice(operands1)
operand2 = random.choice(operands2)
operator = random.choice(operators)
user_answer = int(inputnumber('{} {} {} = '.format(operand1, operator, operand2)))
question += 1
Issues
First, you should declare function definitions outside of your script and call the function by identifier 'inputNumber()'
Also notice the slight change in Try/Except, and the PEP 8 Style Guide compliant formatting.

Python: Mad Libs

Hi I have this project of Mad libs but I donĀ“t know how to make a function that ask the user what level of difficulty between easy, medium or hard they want, and depending on their answer redirect them to the desired level of mad libs. This is what I have so far. Thanks.
parts_of_speech_words = ["VERB","PLACE","ADJECTIVE","NOUN","PLURALNOUN","ADVERB"]
level_easy = """I __VERB__ to go to the __PLACE__
but I don't go in the __ADJECTIVE__
I am __ADJECTIVE__ of the __NOUN__
and getting __VERB__ by a __NOUN__."""
level_medium = """Begging to hear __NOUN__
My ears remain __ADJECTIVE__
__NOUN__ for signs
my __NOUN__ remain __VERB__
Yet __NOUN__still VERB."""
level_hard = """I __VERB__ you without __NOUN__
how, or when, or from where,
I love you __ADVERB__,
without __PLURALNOUN__ or pride;
So I love you because I know
no other way that this:
Where I does not VERB, nor you,
so close that your NOUN
on my chest is my hand,
so close that your NOUN close
as I fall ADJECTIVE."""
greeting = raw_input ("Welcome to mad libs, What's your name? ")
prompt = raw_input ("Select your level: easy, medium or hard: ")
def entry_level_prompt (variable_level):
easy = level_easy
medium = level_medium
hard = level_hard
for e in variable_level:
if prompt == easy:
return level_easy
print level_easy
if prompt == medium:
return level_medium
print level_medium
if prompt == hard:
return level_hard
print lever_hard
print "Ok %s you chose the %s level" % (greeting , prompt)
print entry_level_prompt (variable_level)
def parts_of_speech (words_string, list_of_part_of_speech):
for pos in list_of_part_of_speech:
if pos in words_string:
return pos
return None
def play_mad_libs (split_string, list_of_part_of_speech):
replaced = []
split_string = split_string.split ()
for words_string in split_string:
replacement = parts_of_speech (words_string, list_of_part_of_speech)
if replacement != None:
user_input = raw_input ("Type in a: " + replacement + " ")
words_string = words_string.replace (replacement, user_input)
replaced.append(words_string)
else:
replaced.append(words_string)
replaced = " ".join(replaced)
return replaced
print play_mad_libs (entry_level_prompt, parts_of_speech_words)
You have a bug in your code. You are calling entry_level_prompt(variable_level) but variable_level does not exist outside of the method scope.
To control the difficulty, you can create a method called get_difficulty()
def get_difficulty():
choice = ""
while choice not in ('easy', 'medium', 'hard'):
choice = raw_input("choose your difficulty: ")
if choice == "easy":
return level_easy
elif choice == "medium":
return level_medium
elif choice == "hard":
return level_hard
else:
print("Invalid choice...")
You've confused the selector -- "easy", "medium", or "hard" -- with the variable you want to return -- level_easy, level_medium, or level_hard. You cannot use the variable prompt for both purposes at the same time.
I recommend that you keep variable prompt as you started: it holds the user input. Then, simply test it and return the needed script:
if prompt == "easy":
return level_easy
elif prompt == "medium"
return level_medium
elif prompt == "hard"
return level_hard
else:
"Please enter easy, medium, or hard for the level."

Entering the correct length of password restarts my program?

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

Checking whether user has input a number or not?

I made a simple script which finds the Square root of a number. The user inputs a number and it finds the square root and shows the result. I want it to check whether the input was a number or not. If it was a number it'll continue else it'll show a message, and reset.
I tried using:
while num != int(x):
print "That is not a valid number"
return self.page()
But that only shows an error.
Can someone help me out on this?
Here is the code:
import math
import sys
class SqRoot(object):
def __init__(self):
super(SqRoot, self).__init__()
self.page()
def page(self):
z = 'Enter a number to find its square root: '
num = int(raw_input(z))
sqroot = math.sqrt(num)
print 'The square root of \'%s\' is \'%s\'' % (num, sqroot)
choose = raw_input('To use again press Y, to quit Press N: ')
if choose == 'Y' or choose == 'y':
return self.page()
elif choose == 'N' or choose == 'n':
sys.exit(0)
print "SqRoot Finder v1.0"
print "Copyright(c) 2013 - Ahnaf Tahmid"
print "For non-commercial uses only."
print "--------------------------------"
def main():
app = SqRoot()
app()
if __name__ == '__main__':
main()
One of the python principles is EAFP:
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false.
x = raw_input('Number?')
try:
x = float(x)
except ValueError:
print "This doesn't look like a number!"
If you don't want to use the ask forgiveness method, here is a simple function which should work on any valid float number.
def isnumber(s):
numberchars = ['0','1','2','3','4','5','6','7','8','9']
dotcount=0
for i in range(len(s)):
if (i==0 and s[i]=='-'):
pass
elif s[i]=='.' and dotcount==0:
dotcount+=1
elif s[i] not in numberchars:
return False
return True
Note: You can add base 16 easy by changing numberchars to:
numberchars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']

Categories

Resources