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.😔")
Exemple #2
0
 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()
Exemple #3
0
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",
        )
Exemple #4
0
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
Exemple #7
0
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",
    )
Exemple #8
0
    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"
Exemple #9
0
    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)
Exemple #10
0
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)
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 
Exemple #12
0
    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}
Exemple #14
0
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.'})
Exemple #15
0
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})
Exemple #16
0
 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)}"
     )
Exemple #17
0
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))
Exemple #18
0
def get_password(wordlen, digitlen, words, strength):
    """
    Get and return a single password
    """

    while True:

        try:
            w = words.pop().capitalize()
        except IndexError:
            sys.exit("Unable to get a sufficiently strong password")

        s = np.random.choice(SPECIAL_CHARS)
        i = np.random.randint(0, 10**digitlen)

        comp = [w, f"{i:0{digitlen}d}", s, s]
        np.random.shuffle(comp)
        pw = ''.join(comp)

        #       pw = str(f"{s}{w}{i:0{digitlen}d}{s}")
        stats_pw = PasswordStats(pw)

        if stats_pw.strength() >= strength:
            return pw, stats_pw
Exemple #19
0
        if len(al) > 4:
            break

def slicing():
    name = na[0:4]
    alias = al[0:4]
    global full
    full = "".join(name.title()) + random_symbol + alias.title() + random_symbol2 + random_string + str(random_number)
    return
slicing()

print("This is your password ", full)
print("Your password is ", len(full), "chars long")
print("Let s improve the following:", policy.test(full))
stats = PasswordStats(full)
print("Here is the password strength:", stats.strength())

if stats.strength() > 0.66:
    print("Your password is strong")
else:
    print("Your password is weak, try more complex inputs")

hash_object = hashlib.md5(full.encode())
md5_hash = hash_object.hexdigest()
hash_object1 = hashlib.sha256(full.encode())
sha256 = hash_object1.hexdigest()
hash_object2 = PasswordHasher()
argon2 = hash_object2.hash(full)

if stats.strength() > 0.66:
    print("This is the MD5 hash of your password: ", md5_hash)
def check_password_strength(password: str, minimum: float) -> bool:
    stats = PasswordStats(password)
    return stats.strength() >= minimum
Exemple #21
0
import csv
from password_strength import PasswordStats
dataset = open(r"Datasets/xatoBig.txt", "r", encoding='latin-1')
new_dataset = open("Datasets/Processed/length.txt",
                   "w",
                   encoding='latin-1',
                   newline='')
write = csv.writer(new_dataset)
write.writerow(["Password", "Complexity", "Length", "Code"])
for i in dataset:
    stats = PasswordStats(i)
    i = i.replace("\n", "")
    if stats.strength() < 0.3:
        x = 0
    elif stats.strength() < 0.5:
        x = 1
    elif stats.strength() < 0.7:
        x = 2
    else:
        x = 3
    val = i + "," + str(stats.strength()) + "," + str(x) + ","
    print(val)
    write.writerow([i, stats.strength(), len(i), x])
new_dataset.close()
Exemple #22
0
import pandas as pd
import numpy as np
import matplotlib.pyplot  as plt
import csv
import seaborn as sns
from password_strength import PasswordStats

dataset = pd.read_csv(r"PreProcess/Datasets/Logistic/exp.txt")
print(dataset)
X = dataset.iloc[:, 1].values
y = dataset.iloc[:, 3].values
print("Complexity", X)
print("Breached", y)
X_pass = input("Enter Your Password")
stats = PasswordStats(X_pass)
X_test = [[stats.strength()]]
print(X_test)
# Splitting the data set into Training and Test set
'''from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=0)
X_train = X_train.reshape(-1, 1)
y_train = y_train.ravel()
X_test=X_test.reshape(-1,1)

print("X TRAIN",X_train)
print("X TEST",X_test)
print("Y TRAIN",y_train)
print("Y TEST",y_test)'''
X_train = X.reshape(-1, 1)
y_train = y.ravel()
def statChecker(passwordString):
	stats = PasswordStats(passwordString)
	strength = stats.strength()
	print(strength)
# In[2]:

from password_strength import PasswordStats  #import library to test the strength of the passwords
import string  #to create a string of punctuations
import random  #to be able to shuffle everything
Name = input(
    "Welcome! Let's create a random password for you! Please insert your name: "
)
Birth = input(
    f"Ok, {Name}! I will use the letters of your name in your password! Please insert also your birth year: "
)
Info = Name + Birth
passwordlength = 16
Punct_number = 16 - len(Info)  #the number of punctuation symbols I need
punctelements = "".join(
    random.choice(string.punctuation) for i in range(
        Punct_number))  #create the correct number of string of punct symbols
Passwordelements = Info + punctelements  #put everything together
Password = "".join(random.sample(
    Passwordelements, 16))  #shuffling and creating a string with 16 characters
print(
    f"Here is your random password: {Password}, it's a mix of the letters of your name, the numbers in your birth year and some random punctuations!"
)
stats = PasswordStats(Password)
y = stats.strength()  #strength of the generated password
print(
    f"The strength of your password is: {y}. It's recommended for it to be at least 0.66 to be considered strong."
)

# In[ ]:
name = input("Welcome! Let's create a random password for you!\
     Please insert your name: ")
birth = input(f"Ok, {Name}! I will use the letters of your name in\
     your password! Please insert also your birth year: ")
info = name + birth

# determine password length and the number of punctuation symbols I need:
passwordlength = 16
punct_number = 16 - len(info)

# create the correct number of string of punct symbols:
punctelements = "".join(
    random.choice(string.punctuation) for i in range(punct_number))

# merge the user input and punctuation symbols:
passwordelements = info + punctelements

# shuffle the string created above:
password = "".join(random.sample(passwordelements, 16))

print(f"Here is your random password: {password}, it's a mix of the\
    letters of your name, the numbers in your birth year\
         and some random punctuations!")
stats = PasswordStats(password)
# strength of the generated password:
y = stats.strength()
print(f"The strength of your password is: {y}. It's recommended for it to be\
     at least 0.66 to be considered strong.")

# In[ ]: