def validar_password(password1, password2): if not password1 == password2: raise ValidationError("password: Las contraseñas no coinciden") errors = [] # password strength. Value range [0 : 1] if PasswordStats(password1).strength() < PASSWORD_STRENGTH: errors.append('Fortaleza: La contraseña es muy simple.') # Min length: 8 if PasswordStats(password1).length < PASSWORD_LENGTH: errors.append(f'Tamaño: La contraseña debe tener al menos {PASSWORD_LENGTH} caracteres.') # Need min. 1 number if PasswordStats(password1).numbers < PASSWORD_NUMBERS: errors.append(f'Numeros: La contraseña debe tener al menos {PASSWORD_NUMBERS} número.') # Need min. 1 uppercase letters if PasswordStats(password1).letters_uppercase < PASSWORD_UPPERCASE: errors.append(f'Mayúscula: La contraseña debe tener al menos {PASSWORD_UPPERCASE} mayúscula.') # Need min. 1 special characters if PasswordStats(password1).special_characters < PASSWORD_SPECIAL: errors.append(f'Especial: La contraseña debe tener al menos {PASSWORD_SPECIAL} caracater especial.') if errors: raise ValidationError(errors)
def get_password_weaknesses(pw, username=None): errors = [] stats = PasswordStats(pw) LEN = 12 MIN_STRENGTH = 0.50 MIN_ENTROPY_BITS = 30 if stats.length < LEN: errors.append( f"Password is too short - go for something longer than {LEN} characters" ) if stats.strength() < MIN_STRENGTH: errors.append( f"Password is too simple - current strength is {stats.strength():.2g}, you need at least {MIN_STRENGTH}" ) if stats.entropy_bits < MIN_ENTROPY_BITS: errors.append( f"Password is too simple - currently it has {stats.entropy_bits} entropy bits, you need at least {MIN_ENTROPY_BITS}" ) if pw in FREQUENT_PASSWORDS: errors.append( "This password is already on a list of common passwords, make up something else" ) if username and username in pw.lower(): errors.append( "Your username is present in the password, make up something else") if not pw.isascii(): errors.append( "Don't use characters outside of the US keyboard in your password - in other words, use only ASCII printable characters in your password definition" ) if errors: errors.append(PASSWORD_HINT) return errors
def check(): if entry.get() == "": messagebox.showinfo("Error", "Password can't be empty") else: result = PasswordStats(entry.get()) final = result.strength() label1["text"] = str(math.ceil(final * 100)) + " %" if final >= 0.66: w.create_rectangle(105, 50, 300, 100, fill="#27cf54", outline="white") elif final > 0.10 and final < 0.40: w.create_rectangle(105, 50, 300, 100, fill="#f0f007", outline="white") elif final <= 0.10: w.create_rectangle(105, 50, 300, 100, fill="#de3c3c", outline="white")
def validate_password_strength(password): if password is not None: stats = PasswordStats(password) if stats.strength() < SECURE_PASSWORD_STRENGTH: raise ValueError( "Your password is insecure. " "Try adding more symbols or numbers, mixing upper and lower case, " "and having a longer password.") return password
async def hi(event): if event.fwd_from: return okbabe = secrets.token_urlsafe(16) stats = PasswordStats(okbabe) sedbruh = stats.strength() await event.edit( f"<b>Password</b> : <code>{okbabe}</code> \n<b>Strength :</b> <code>{sedbruh}</code>", parse_mode="HTML", )
def examine_password_for_complexity(self): stats = PasswordStats(self.__user.password) complexity = stats.strength() if 0 <= complexity < 0.33: return "weak" elif 0.33 <= complexity < 0.66: return "medium" elif 0.66 <= complexity < 1: return "strong"
def test_count(self): s = PasswordStats('aAA111!!!!°°°°° \0') self.assertEqual(s.length, 22) self.assertEqual(s.letters, 3) self.assertEqual(s.letters_lowercase, 1) self.assertEqual(s.letters_uppercase, 2) self.assertEqual(s.numbers, 3) self.assertEqual(s.count('L', 'N'), 3 + 3) self.assertEqual(s.special_characters, 4 + 5 + 6 + 1)
def test_count(self): s = PasswordStats(u'aAA111!!!!°°°°° \0') self.assertEqual(s.length, 22) self.assertEqual(s.letters, 3) self.assertEqual(s.letters_lowercase, 1) self.assertEqual(s.letters_uppercase, 2) self.assertEqual(s.numbers, 3) self.assertEqual(s.count('L', 'N'), 3+3) self.assertEqual(s.special_characters, 4+5+6+1)
async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) stats = PasswordStats(input_str) stats.strength() if stats.strength() >= 0.6: await event.edit("Good Password. 😎") else: await event.edit("bad password, change it.😔")
def __call__(self, form, field): password_policy = PasswordStats(field.data) strength = password_policy.strength() length = len(field.data) message = u'Your password must contains at least 8 characters with numbers and capital letters' if length < 8 or password_policy.letters_uppercase < 1 or password_policy.numbers < 1: raise ValidationError(message) message = u'Your password is not strong enough' if strength < 0.25: raise ValidationError(message)
def password_strength(password): stats = PasswordStats(password) strength = stats.strength() if strength >= 0.80: print("This is a very strong password!") elif strength >= 0.50 and strength <= 0.80: print("This is a medium strength password. Consider increasing complexity.") else: print("This is a weak password. Highly consider increasing the complexity") return strength
def passwordStrength(password): from password_strength import PasswordStats stats = PasswordStats(password) strength = round(stats.strength(), 3) x = "Password strength [{}/0.999] -> ".format(strength) if 0.0 <= strength and strength <= 0.333: x += "[weak]" elif 0.334 <= strength and strength <= 0.666: x += "[medium]" else: x += "[strong]" print(x)
async def enforce_strength(password: str, strength_percentage: float): """ enforces password to have specified strength percentage @param password: (str) to enforce strength @param strength: (float) cut off strength percentage """ stats = PasswordStats(password) if stats.strength() < strength_percentage: raise Exception({ 'message': 'Password strength not up to standard', 'status_code': 400 })
def gen_password_strength(): """ This function request the user for his password and calculates the strength and the flag of the password strength with help of password_strength library :return: """ print("Please type in your password (to assess it's strength") password = input() stats = PasswordStats(password) print(f"your password strength is: {stats.strength()}") return {"password_strength": stats.strength()>=0.6}
def passTry(passStat): Stat = PasswordStats(passStat) passwordweak = 'None' for file in Score.filelist: try: with open(file + '.txt', mode='r') as fp: for line in fp: if passStat == line.rstrip('\n'): passwordweak = file fp.close() return passwordweak, Stat.strength() fp.close() except OSError: print('File: ' + file + '.txt' + ' failed to load.') return passwordweak, Stat.strength()
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["password"] = self.request.session.get("strength_password", "") context["entropy"] = PasswordStats(context["password"]).entropy_bits if context["password"] else 0 return context
def ChangePassword(request): user = request.user old_password = request.data.get('opassword') new_password = request.data.get('npassword') if not old_password: return Response({'error': 'old password is required !'}, status=400) if not new_password: return Response({'error': 'new password is required !'}, status=400) if not authenticate(username=user.username, password=old_password): return Response({'error': 'password is incorrect !'}, status=400) stats = PasswordStats(new_password) if stats.strength() < 0.250: return Response({'error': 'Weak password !'}, status=400) user.password = make_password(new_password) user.save() return Response({'response': 'your password changed successfully.'})
async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) stats = PasswordStats(input_str) sedbruh = stats.strength() if stats.strength() >= 0.2: await event.edit( f"<b><u>Password Checked</b></u> \n<b>Password :</b> <code>{input_str}</code> \n<b>Strength :</b> <code>{sedbruh}</code> \n<b>Result :</b> <code>Good Password</code>", parse_mode="HTML", ) else: await event.edit( f"<b><u>Password Checked</b></u> \n<b>Password :</b> <code>{input_str}</code> \n<b>Strength :</b> <code>{sedbruh}</code> \n<b>Result :</b> <code>Bad Password</code>", parse_mode="HTML", )
def update_password(current_password=Form(...), new_password=Form(...), user=Depends(manager), db: database.Session = Depends(database.get_db)): if not user: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail='Not authenticated') elif len(new_password) < 7: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Password must be 8 characters or more') elif len(new_password) >= 40: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail='Password is too long. Maximum length: 40 characters') elif PasswordStats(new_password).strength() <= float(0.350): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail= 'Password is not strong enough. Try adding some symbols or numbers your password' ) else: db_user = db.query( database.User).filter_by(username=user.username).first() if database.Hash.verify_password(current_password, db_user.password): db_user.password = database.Hash.get_password_hash(new_password) db.commit() db.refresh(db_user) return {'detail': 'Passwored changed'} else: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Current password is incorrect')
def signup(request): username = request.data.get('username') password = request.data.get('password') if not username: return Response({'error': 'username is required !'}, status=400) if not password: return Response({'error': 'password is required !'}, status=400) if not username_validator.search(username): return Response({'error': "invalid username !"}, status=400) stats = PasswordStats(password) if stats.strength() < 0.250: return Response({'error': 'Weak password !'}, status=400) try: User.objects.get(username=username) return Response({'error': 'That username is already taken !'}, status=400) except User.DoesNotExist: User.objects.create(username=username, password=make_password(password)) return Response({'username': username})
def passrun(): distances = [] password = input("Enter the Password to be Tested ") pass_len = len(password) pass_complex = PasswordStats(password).strength() for i in range(kmeans.n_clusters): p1 = (kmeans.cluster_centers_[i]) p2 = (pass_len, pass_complex) d = distance.euclidean(p1, p2) distances.append(d) # print(distances) clus_names = [ 'Highly Breachable', 'Partially Unbreachable', 'Partially Breachable', 'Highly UnBreachable' ] low = distances.index(min(distances)) print("Your Password Belong to the Category of ") print(clus_names[low]) # Visualising the clusters plt.scatter(x[y_kmeans == 0, 0], x[y_kmeans == 0, 1], s=100, c='red', label='Very Weak') plt.scatter(x[y_kmeans == 1, 0], x[y_kmeans == 1, 1], s=100, c='orange', label='Good') plt.scatter(x[y_kmeans == 2, 0], x[y_kmeans == 2, 1], s=100, c='blue', label='Week') plt.scatter(x[y_kmeans == 3, 0], x[y_kmeans == 3, 1], s=100, c='green', label='Great') plt.scatter(pass_len, pass_complex, c='pink', label='Your Password', s=300) plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=200, c='black', label='Centroids') plt.ylabel('Complexity') plt.xlabel('Length of Passwords') plt.legend() plt.show() ans = input("Try a new Password?? Y or N ") if ans == 'Y': passrun()
async def password_strength(self, ctx, password: str): """Validate a passwords strength.""" conv = PasswordStats(password) converter = conv.strength() if converter < 0.250: emoji = RED_CIRCLE text = "This is a **weak** password." elif converter > 0.250 and converter < 0.500: emoji = ORANGE_CIRCLE text = "This is an **okay** password." elif converter > 0.500 and converter < 0.750: emoji = YELLOW_CIRCLE text = "This is a **good** password!" else: emoji = GREEN_CIRCLE text = "This is an **excellent** password!" await ctx.send( f"**Strength rating: {round(converter * 100)}%** {emoji}\n{cf.quote(text)}" )
def flashPassword(password): stats = PasswordStats(password) if stats.length < 8: flash('Your password must be at least 8 characters long.') if stats.letters_uppercase < 1: flash('Your password must have at least 1 uppercase character.') if stats.numbers < 1: flash('Your password must have at least 1 number.')
def check_the_password(password): password = int(round(PasswordStats(password).strength(), 2) * 100) if password < 33: prefix = 'The password is week - ' strength_color = 'danger' elif password < 66: prefix = 'The password is Ok - ' strength_color = 'info' else: prefix = 'The password is strong - ' strength_color = 'success' return f"{prefix}{password}%", strength_color
def isValidPassword(password): stats = PasswordStats(password) if stats.length < 8: return False if stats.letters_uppercase < 1: return False if stats.numbers < 1: return False return True
def test_statistics(self): self.assertEqual(PasswordStats('123444').alphabet, set('1234')) self.assertEqual(PasswordStats('!аб!').alphabet, set('!аб')) self.assertEqual(PasswordStats('123444').alphabet_cardinality, 4) self.assertEqual(PasswordStats('!аб!').alphabet_cardinality, 3) self.assertEqual( dict( PasswordStats( 'aAA111!!!!°°°°° \0').char_categories_detailed), { 'Ll': 1, 'Lu': 2, 'Nd': 3, 'Po': 4, 'So': 5, 'Zs': 6, 'Cc': 1 }) self.assertEqual( dict(PasswordStats('aAA111!!!!°°°°° \0').char_categories), { 'L': 3, 'N': 3, 'P': 4, 'S': 5, 'Z': 6, 'C': 1 })
def test_detectors(self): self.assertEqual( PasswordStats('abcabc-1234').repeated_patterns_length, 6) self.assertEqual( PasswordStats('abcabcab-1234').repeated_patterns_length, 6) self.assertEqual( PasswordStats('abcabcabc-1234').repeated_patterns_length, 9) self.assertEqual(PasswordStats('qazwsx').sequences_length, 0) self.assertEqual(PasswordStats('qw...').sequences_length, 0) # Does not detect 2-character sequences self.assertEqual(PasswordStats('qwe...').sequences_length, 3) self.assertEqual(PasswordStats('qwerty...').sequences_length, 6) self.assertEqual( PasswordStats('ZZqwertyZZ1234...').sequences_length, 10)
def get_data(): if request.method == "POST": X_pass = request.form["password"] import pandas as pd from password_strength import PasswordStats dataset = pd.read_csv(r"exp.txt") X = dataset.iloc[:, 1].values y = dataset.iloc[:, 3].values stats = PasswordStats(X_pass) X_test = [[stats.strength()]] # Splitting the data set into Training and Test set X_train = X.reshape(-1, 1) y_train = y.ravel() # Feature Scaling from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) # Fitting the simple linear regression to the training set from sklearn.linear_model import LogisticRegression classifier = LogisticRegression(random_state=0) classifier.fit(X_train, y_train) # Predicting Test Set Results y_pred = classifier.predict(X_test) f = y_pred[0] if f == 1: output = " breached category try another password" else: output = " Unbreached category go with it" return render_template( 'class.html', prediction_text='Your Password belongs to{}'.format(output))
def signup(username=Form(...), email=Form(...), password=Form(...), db: database.Session = Depends(database.get_db)): if db.query(database.User).filter_by(username=username).first(): raise HTTPException(status_code=status.HTTP_302_FOUND, detail='Username taken') elif db.query(database.User).filter_by(email=email).first(): raise HTTPException(status_code=status.HTTP_302_FOUND, detail='Email address already in use') elif len(username) <= 3: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Username must be longer than 3 characters') elif len(username) >= 25: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail='Username is too long. Maximum length: 25 characters') elif len(password) < 7: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='Password must be 8 characters or more') elif len(password) >= 40: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail='Password is too long. Maximum length: 40 characters') elif PasswordStats(password).strength() <= float(0.350): raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail= 'Password is not strong enough. Try adding some symbols or numbers your password' ) elif len(email) >= 75: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail='Email is too long. Must be less than 75 characters') try: valid = validate_email(email) email = valid.email except EmailNotValidError as e: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail='Email address not supported. Please use another email.') else: pwd_hash = Hash.get_password_hash(str(password)) db_user = database.User(username=username, email=email, password=pwd_hash) db.add(db_user) db.commit() db.refresh(db_user) return models.User(username=username, email=email, password=password)
def validate_password(self, value): errors = [] if PasswordStats(value).strength() < password_validators["strength"]: errors.append({'strength': 'The password is very simple.'}) if PasswordStats(value).length < password_validators["length"]: errors.append({ 'length': 'The password must be at least {} characters.'.format( password_validators["length"]) }) if PasswordStats(value).numbers < password_validators["numbers"]: errors.append({ 'numbers': 'The password must have at least {} numbers.'.format( password_validators["numbers"]) }) if PasswordStats( value).letters_uppercase < password_validators["uppercase"]: errors.append({ 'uppercase': 'The password must have at least {} uppercase letters.'.format( password_validators["uppercase"]) }) if PasswordStats( value).special_characters < password_validators["special"]: errors.append({ 'special': 'The password must have be at least {} special characters.'. format(password_validators["special"]) }) if errors: raise ValidationError(errors)
def checkPassword(self, password): results = [] if len(password) < 6: msg = "Password should be at least 6 characters" passwordStrongLevel = PasswordStats(password) results.append(msg) results.append(passwordStrongLevel) elif not re.search("[a-z]", password): msg = "Add at least one lowecase for stronger password" passwordStrongLevel = PasswordStats(password) results.append(msg) results.append(passwordStrongLevel) elif not re.search("[0-9]", password): msg = "Add at least one number for stronger password" passwordStrongLevel = PasswordStats(password) results.append(msg) results.append(passwordStrongLevel) elif not re.search("[A-Z]", password): msg = "Add at least one upercase for stronger password" passwordStrongLevel = PasswordStats(password) results.append(msg) results.append(passwordStrongLevel) elif not re.search("[#@<>_,!?;$%^&*]", password): msg = "Add at least one symbol for stronger password" passwordStrongLevel = PasswordStats(password) results.append(msg) results.append(passwordStrongLevel) else: msg = "Your password is Valid" passwordStrongLevel = PasswordStats(password) results.append(msg) results.append(passwordStrongLevel) return results # class PasswordStronLevelValidator: # msg = "" # def checkStrongLevelPassword(self, password): # if len(password) < 6 or len(password) > 10: # passwordStrongLevel = PasswordStats(password) # elif not re.search("[a-z]", password): # passwordStrongLevel = PasswordStats(password) # elif not re.search("[0-9]", password): # passwordStrongLevel = PasswordStats(password) # elif not re.search("[A-Z]", password): # passwordStrongLevel = PasswordStats(password) # elif not re.search("[#@<->,!?;$%^&*_]", password): # passwordStrongLevel = PasswordStats(password) # else: # passwordStrongLevel = PasswordStats(password) # return passwordStrongLevel