Example #1
0
def signup():
    result = None
    if request.method == 'POST':
        uname = request.form.get("uname")
        uemail = request.form.get("uemail")
        upass = request.form.get("upass")
        urepass = request.form.get("urepass")
        strength, improvements = passwordmeter.test(upass)
        if uname is None or uemail is None or upass is None or urepass is None:
            result = "some fields are vacent,fill the form completely."
            return render_template('signup.html', result=result)  # , improvements=improvements)
        elif urepass != upass:
            result = "password doesn't match, try again."
            return render_template('signup.html', result=result)  # , improvements=improvements)
        elif strength < 0.5:
            result = "password is very weak."
            return render_template('signup.html', result=result,
                                   improvements=improvements)

        elif strength < 0.8:
            result = "password is weak."
            return render_template('signup.html', result=result,
                                   improvements=improvements)

        elif strength > 0.8:
            return redirect(url_for('login'))
    return render_template('signup.html')
def main():
    CodedPasswords = []
    PWs = []
    STRENGTHs = []
    file = open("Shortpws.txt", "r")
    for line in file:
        line = line.rstrip("\n")
        TSS = []
        cnt = 0
        strength, improvements = passwordmeter.test(line)
        cnt += 1
        TSS.append(line)
        PWs.append(line)
        TSS.append(strength * 100)
        STRENGTHs.append(int(round(strength * 100)))
        # TSS.append(strength)
        CodedPasswords.append(TSS)
    print(CodedPasswords)
    vectorizer = TfidfVectorizer(tokenizer=getTokens)
    X = vectorizer.fit_transform(PWs)
    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        STRENGTHs,
                                                        test_size=0.20,
                                                        random_state=42)
    lgs = LogisticRegression(penalty='l2', multi_class='ovr')
    lgs.fit(X_train, y_train)
    print(lgs.score(X_test, y_test))
Example #3
0
async def check_password_strength(request: web.Request):
    """ evaluates password strength and suggests some recommendations

        The strength of the password in the range from 0 (extremely weak) and 1 (extremely strong).

        The recommendations is a dictionary of ways the password could be improved.
        The keys of the dict are general "categories" of ways to improve the password (e.g. "length")
        that are fixed strings, and the values are internationalizable strings that are human-friendly descriptions
        and possibly tailored to the specific password
    """
    params, _, _ = await extract_and_validate(request)
    password = params['password']

    #TODO: locale = params.get('locale') and translate message accordingly
    strength, improvements = passwordmeter.test(password)
    ratings = ('Infinitely weak', 'Extremely weak', 'Very weak', 'Weak',
               'Moderately strong', 'Strong', 'Very strong')

    data = {
        'strength': strength,
        'rating': ratings[min(len(ratings) - 1, int(strength * len(ratings)))]
    }
    if improvements:
        data['improvements'] = improvements
    return data
def PasswordChecker(clear_password):
    """This function checks if the password to create is secure
    @param clear_password The password to examinate
    @return the password if the test pass or an error message if the test fails
    """
    # if the password is too short
    if len(clear_password) <= 5:
        return "This password is too short, the password " + \
            "must be at least 6 characters", HTTP_NOT_ACCEPTABLE
    # if the password is too common
    f = open(PASSWORD_NOT_ACCEPTED_DATA)
    lines = f.readlines()
    f.close()
    for line in lines:
        for word in line.split():
            if clear_password == word:
                return "This password is too common, the password " + \
                    "must be something unusual", HTTP_NOT_ACCEPTABLE
    # if the password is too easy
    strength, _ = passwordmeter.test(clear_password)
    if strength < 0.5:
        return "This password is too easy, the password should " + \
            "be a combination of numbers, uppercase and lowercase" + \
            "characters and special characters", HTTP_NOT_ACCEPTABLE
    return clear_password
Example #5
0
    def post(self, username):
        """
        A not-logged user is asking to register himself.
        NB: username must be a valid email address.
        """
        if username in userdata:
            abort(HTTP_CONFLICT)

        password = request.form['password']
        strength, improvements = passwordmeter.test(password)
        if strength <= 0.5:
            return improvements, HTTP_FORBIDDEN
        activation_code = os.urandom(16).encode('hex')

        # Composing email
        subject = '[{}] Confirm your email address'.format(__title__)
        sender = 'donotreply@{}.com'.format(__title__)
        recipients = [username]
        text_body_template = string.Template(_read_file(SIGNUP_EMAIL_TEMPLATE_FILE_PATH))
        values = dict(code=activation_code,
                      email=username,
                      appname=__title__,
                      )
        text_body = text_body_template.substitute(values)

        send_email(subject, sender, recipients, text_body)

        pending_users[username] = {
            'timestamp': now_timestamp(),
            'activation_code': activation_code,
            PWD: password,
        }
        return 'User activation email sent to {}'.format(username), HTTP_OK
Example #6
0
def main():
    print(
        "How many words, numbers and special characters you want? (e.g 4 8 3)")
    num_words, num_numbers, num_special = map(int, input().split())
    pass_str = create_password(num_words, num_numbers, num_special)
    strength, _ = test(pass_str)
    print('Password: %s' % pass_str)
    print("\nPassword's Strength: %0.5f" % strength)
Example #7
0
def passwd_test(passwd):
    test = pwm.test(passwd)
    result = {
        'passwd': passwd,
        'score': test[0],
        'suggestions': test[1]
    }
    return result
Example #8
0
def genPassword():  # Generating a Strong password of length = 16
    m = ''  # m is the password string
    passwordStrength = 0
    while passwordStrength <= 0.8 and len(m) < 16:
        for _ in range(16):
            m = m + X[random.randint(0, len(X) - 1)]
        passwordStrength = passwordmeter.test(m)[0]
    return m
Example #9
0
def checkPasswordStrength(password):
    strength, improvements = passwordmeter.test(password)
    if strength < minPwStrength:
        logger.error("Password too weak: %f", strength)
        for i in improvements:
            logger.info("    %s", improvements[i])
        return False
    else:
        return True
Example #10
0
def checkPasswordStrength(password):
    strength, improvements = passwordmeter.test(password)
    if strength < minPwStrength:
        logger.error("Password too weak: %f", strength)
        for i in improvements:
            logger.info("    %s", improvements[i])
        return False
    else:
        return True
Example #11
0
def checkPasswordStrength(password):
    pwStrMin     = float(Defaults.getDefault('TARDIS_PW_STRENGTH'))
    strength, improvements = passwordmeter.test(password)
    if strength < pwStrMin:
        logger.error("Password too weak: %f (%f required)", strength, pwStrMin)
        for i in improvements:
            logger.error("    %s", improvements[i])
        return False
    else:
        return True
def main():
 pass_str=create_password()
 pass_str1=list(pass_str)
 shuffle(pass_str1)
 pass_str2=''.join(pass_str1)
 strength,_=test(pass_str2)
 print("PASSWORD: %s"%pass_str2)
 #checks the strength of password 
 print("STRENGTH: %0.5f"%strength)
 print(password_check(pass_str2))
Example #13
0
def checkPasswordStrength(password):
    pwStrMin     = float(Defaults.getDefault('TARDIS_PW_STRENGTH'))
    strength, improvements = passwordmeter.test(password)
    if strength < pwStrMin:
        logger.error("Password too weak: %f (%f required)", strength, pwStrMin)
        for i in improvements:
            logger.error("    %s", improvements[i])
        return False
    else:
        return True
Example #14
0
def main():
    # password parameters from pipe
    _words_count = param[1] if len(param) > 1 else 0
    _numbers_count = param[2] if len(param) > 2 else 0
    _special_count = param[3] if len(param) > 3 else 0
    _word_to_use = param[4] if len(param) > 4 else ""

    password = create_password(num_words=_words_count,
                               num_numbers=_numbers_count,
                               num_spcial=_special_count,
                               word_to_use=_word_to_use)
    strength = test(password)[0]
    return (password, strength)
Example #15
0
    def change_db_user_password(self,
                                username,
                                password,
                                db_type,
                                enforce_password_strength=True):
        """Change a DB user's password
        https://docs.webfaction.com/xmlrpc-api/apiref.html#method-change_db_user_password

        Args:
            username (str): database user's name
            password (str): database user's password
            db_type (str): either `mysql` or `postgresql`
            enforce_password_strength (boolean): use passwordmeter to
                ensure strong passwords are used

        Returns:
            Returns an object of type WebFactionDBUser, otherwise False
        """
        assert isinstance(username,
                          string_types), 'username should be a string'
        assert isinstance(password,
                          string_types), 'password should be a string'
        assert isinstance(db_type, string_types), 'db_type should be a string'

        if enforce_password_strength:
            strength, improvements = passwordmeter.test(password)
            suggestions = [value for value in improvements.values()]

            if strength < 0.5:
                raise ValueError(
                    "Your password is weak. Suggested improvements: \
                    \n\t{improvements}".format(
                        improvements='\n\t'.join(suggestions)))

        if db_type not in self.valid_db_types:
            raise ValueError(
                "db type should be either: {valid_db_types}".format(
                    valid_db_types=', '.join(self.valid_db_types)))

        try:
            result = self.server.change_db_user_password(
                self.session_id, username, password, db_type)
            self.logger.debug(action="change_db_user_password", result=result)

            return WebFactionDBUser(username, password, db_type)
        except xmlrpclib.Fault:
            self.logger.exception(
                message="Could not change password for DB user {name} ({type} \
                    DB)".format(name=username, type=db_type))
            return False
Example #16
0
def create_strong_password():
    passowrd_count = 0
    print("\nGenerating strong password ...\n")

    while True:
        # use 2 english word found in Words.txt
        # use 4 numbers between 0 and 9
        # use 4 symbols using special character list
        password = create_password(num_words=2, num_numbers=4, num_spcial=4)
        strength = test(password)[0]
        passowrd_count += 1

        if strength >= acceptable_strength:
            print(f"Here's a password out of {passowrd_count} generated.")
            show_password(password, strength)
            exit()
Example #17
0
def insert_new_passwd(headers, body, data):
    db, cursor = pysql.database_connect()

    token = str((AuthCookieFactory()).get_from_headers(headers).get_token())
    if token is None:
        return render_template(
            'unauthorised_request.html',
            body=body,
            data=data,
            message='Anauthorised try to change password!'), 200, {}
    cursor.execute('''SELECT login FROM cookie WHERE token=%s''', token)
    login = str(cursor.fetchone()[0])
    passwd = str(data['pw']) if 'pw' in data else ''
    passwd_r = str(data['pw-x']) if 'pw-x' in data else ''

    salt = uuid.uuid4().hex
    salt_bytes = salt.encode('utf-8')
    if passwd == passwd_r:
        strength, improvements = passwordmeter.test(passwd)
        if strength < 0.3:
            return render_template(
                'passwordchange.html',
                body=body,
                data=data,
                login=login,
                message='Your password is too weak!'), 200, {}
        for i in range(3):
            pw_bytes = passwd.encode('utf-8')
            passwd = hashlib.sha512(pw_bytes + salt_bytes).hexdigest()
        cursor.execute(
            '''UPDATE users SET password= %s, salt= %s WHERE login= %s''',
            (passwd, salt, login))
        db.commit()
        db.close()
        IP, time = pysql.print_ip(login)
        return render_template(
            'mainpage.html',
            body=body,
            data=data,
            IP=IP,
            time=time,
            message='You successfully changed your password!'), 200, {}
    else:
        return render_template('passwordchange.html',
                               body=body,
                               data=data,
                               message='Passwords are not match!'), 200, {}
Example #18
0
    def post(self, username):
        """
        A not-logged user is asking to register himself.
        NB: username must be a valid email address.
        """
        if username in userdata:
            abort(HTTP_CONFLICT)

        password = request.form['password']
        strength, improvements = passwordmeter.test(password)
        if strength <= 0.5:
            return improvements, HTTP_FORBIDDEN
        activation_code = os.urandom(16).encode('hex')

        # Composing email
        subject = '[{}] Confirm your email address'.format(__title__)
        sender = 'donotreply@{}.com'.format(__title__)
        recipients = [username]
        text_body_template = string.Template("""
Thanks for signing up for $appname!

As a final step of the $appname account creation process, please confirm the email address $email.
Copy and paste the activation code below into the desktop application:

$code

If you don't know what this is about, then someone has probably entered your email address by mistake.
Sorry about that. You don't need to do anything further. Just delete this message.

Cheers,
the $appname Team
""")
        values = dict(code=activation_code,
                      email=username,
                      appname=__title__,
                      )
        text_body = text_body_template.substitute(values)

        send_email(subject, sender, recipients, text_body)

        pending_users[username] = {
            'timestamp': now_timestamp(),
            'activation_code': activation_code,
            PWD: password,
        }
        return 'User activation email sent to {}'.format(username), HTTP_OK
Example #19
0
def password_search(line):
    try:

        potential_pass_list = re.findall(r"['\">](.*?)['\"<]", line)
        pass_list = []

        for string in potential_pass_list:
            password_complexity = passwordmeter.test(string)[0]

            if (password_complexity >= PASSWORD_COMPLEXITY*0.1) and \
                (not re.search(r"\s", string)) and \
                (MIN_PASS_LENGTH <= len(string) <= MAX_PASS_LENGTH):
                pass_list.append((string, password_complexity))

        return pass_list

    except Exception as e:
        logger.error(e)
def com_string_password_test(password_text):
    """
    Test password strength
    """
    import passwordmeter
    ratings = (
        'Infinitely weak',
        'Extremely weak',
        'Very weak',
        'Weak',
        'Moderately strong',
        'Strong',
        'Very strong',
    )
    strength, improvements = passwordmeter.test(password_text)
    common_global.es_inst.com_elastic_index('info', {'Password strength: {} ({})'.format(
        strength, (ratings[min(len(ratings) - 1, int(strength * len(ratings)))]))})
    return (strength, improvements)
Example #21
0
def password_search(line):
    try:
        potential_pass_list = re.findall(PASSWORD_REGEX, line)
        pass_list = []

        for string in potential_pass_list:
            if (not MIN_PASS_LENGTH <= len(string) <= MAX_PASS_LENGTH) or any(ch.isspace() for ch in string):
                continue

            password_complexity = passwordmeter.test(string)[0]

            if password_complexity < PASSWORD_COMPLEXITY * 0.1:
                continue

            yield (string, password_complexity)

    except Exception as e:
        logger.error(e)
Example #22
0
    def on_entry_changed(self, entry: Gtk.Entry) -> None:
        """React to an entry being changed.

        Removes the 'error' CSS class from the entry.

        Args:
            entry (Gtk.Entry): The changed entry
        """
        if entry is self.password_entry:
            entry.get_style_context().remove_class("error")

            if entry.get_text() == self.password_confirm_entry.get_text():
                self.password_confirm_entry.get_style_context().remove_class(
                    "error")

            if entry.get_text() == "":
                entry.set_progress_fraction(0)
            else:
                strength, improvements = passwordmeter.test(entry.get_text())
                entry.set_progress_fraction(strength)

                if strength > 2 / 3.0:
                    entry.get_style_context().remove_class("bad")
                    entry.get_style_context().remove_class("medium")
                    entry.get_style_context().add_class("good")
                elif strength > 1 / 3.0:
                    entry.get_style_context().remove_class("bad")
                    entry.get_style_context().add_class("medium")
                    entry.get_style_context().remove_class("good")
                else:
                    entry.get_style_context().add_class("bad")
                    entry.get_style_context().remove_class("medium")
                    entry.get_style_context().remove_class("good")

        elif entry is self.password_confirm_entry:
            if entry.get_text() == self.password_entry.get_text():
                entry.get_style_context().remove_class("error")
            else:
                entry.get_style_context().add_class("error")

        elif entry is self.username_entry:
            entry.get_style_context().remove_class("error")
Example #23
0
def PasswordChecker(clear_password):
    # if the password is too short
    if len(clear_password) <= 5:
        return "This password is too short, the password " + \
            "must be at least 6 characters", HTTP_NOT_ACCEPTABLE
    # if the password is too common
    f = open(PASSWORD_NOT_ACCEPTED_DATA)
    lines = f.readlines()
    f.close()
    for line in lines:
        for word in line.split():
            if clear_password == word:
                return "This password is too common, the password " + \
                    "must be something unusual", HTTP_NOT_ACCEPTABLE
    # if the password is too easy
    strength, _ = passwordmeter.test(clear_password)
    if strength < 0.5:
        return "This password is too easy, the password should " + \
            "be a combination of numbers, uppercase and lowercase" + \
            "characters and special characters", HTTP_NOT_ACCEPTABLE
    return clear_password
Example #24
0
def password_search(line, settings):
    try:
        potential_pass_list = re.findall(PASSWORD_REGEX, line)
        pass_list = []
        min_pass = settings.min_pass if settings.min_pass else MIN_PASS_LENGTH
        max_pass = settings.max_pass if settings.max_pass else MAX_PASS_LENGTH
        password_complexity_edge = settings.password_complexity if settings.password_complexity else PASSWORD_COMPLEXITY

        for string in potential_pass_list:
            if (not min_pass <= len(string) <= max_pass) or any(ch.isspace() for ch in string):
                continue

            password_complexity = passwordmeter.test(string)[0]

            if password_complexity < password_complexity_edge * 0.1:
                continue

            yield (string, password_complexity)

    except Exception as e:
        logger.error(e)
Example #25
0
                        def main():
                            password_str = create_password()
                            strength, _ = test(password_str)

                            print(
                                "\n\n\u001b[37m➡️ Your Password: %s \u001b[37m"
                                % password_str)
                            print(
                                "\u001b[37m➡️ Strength Of A Computer To Crack This Password:\u001b[37m %0.5f"
                                % strength +
                                " \033[1;34m{OK Not So Bad}\033[1;m")
                            time.sleep(3)
                            print('\n\u001b[37m[i] End time: %s\u001b[37m' %
                                  time.strftime(
                                      '\u001b[34;1m[%H:%M:%S]\u001b[34;1m'))
                            print(
                                "\n\n\t\t\u001b[32m[◉] Be Carefull It's Not Mean You're Protected! Use The First Option To Create Your Password.\u001b[32m"
                            )
                            input(
                                "\n\n\t\t\t\t\t\033[1;34m▶️ Completed, click return to go back"
                            )
                            CLS()
Example #26
0
    def post(self, username):
        """
        A not-logged user is asking to register himself.
        NB: username must be a valid email address.
        """
        if not validate_email(username):
            return 'Error: username must be a valid email address!', HTTP_BAD_REQUEST

        password = request.form['password']
        if not password:
            return 'Error: the password mustn\'t be empty', HTTP_BAD_REQUEST

        strength, improvements = passwordmeter.test(password)
        if strength <= 0.5:
            return improvements, HTTP_FORBIDDEN
        activation_code = os.urandom(16).encode('hex')

        if username in userdata:
            # If an user is pending for activation, it can't be another one with the same name
            #  asking for registration
            return 'Error: username "{}" already exists!\n'.format(
                username), HTTP_CONFLICT

        # Composing email
        subject = '[{}] Confirm your email address'.format(__title__)
        sender = 'donotreply@{}.com'.format(__title__)
        recipients = [username]
        text_body_template = string.Template(
            _read_file(SIGNUP_EMAIL_TEMPLATE_FILE_PATH))
        values = dict(
            code=activation_code,
            email=username,
            appname=__title__,
        )
        text_body = text_body_template.substitute(values)

        send_email(subject, sender, recipients, text_body)

        return create_user(username, password, activation_code)
Example #27
0
def com_string_password_test(password_text):
    """
    Test password strength
    """
    import passwordmeter
    ratings = (
        'Infinitely weak',
        'Extremely weak',
        'Very weak',
        'Weak',
        'Moderately strong',
        'Strong',
        'Very strong',
    )
    strength, improvements = passwordmeter.test(password_text)
    common_global.es_inst.com_elastic_index(
        'info', {
            'Password strength: {} ({})'.format(
                strength,
                (ratings[min(len(ratings) - 1, int(strength * len(ratings)))]))
        })
    return (strength, improvements)
Example #28
0
    def register():

        if request.form['email'] != request.form['email1']:
            return redirect(url_for('new', message='email'))

        if request.form['password'] != request.form['password']:
            return redirect(url_for('new', message='password'))

        if passwordmeter.test(request.form['password'])[0] < 0.4:
            return redirect(url_for('new', message='password_weak'))

        l = len(request.form['fullname'])
        if l < 1 or l > 40:
            return redirect(url_for('new', message='fullname_invalid'))

        User.create(
            request.form['email'],
            request.form['password'],
            fullname=request.form['fullname'],
        ).save()

        return redirect(url_for('index', message='register_success'))
Example #29
0
def insert_new_password(headers, body, data):
    login = str(data['name']) if 'name' in data else ''
    passwd = str(data['pw']) if 'pw' in data else ''
    passwd_r = str(data['pw-x']) if 'pw-x' in data else ''

    salt = uuid.uuid4().hex
    salt_bytes = salt.encode('utf-8')
    if passwd == passwd_r:
        strength, improvements = passwordmeter.test(passwd)
        if strength < 0.3:
            return render_template(
                'passwordchange.html',
                body=body,
                data=data,
                login=login,
                message='Your password is too weak!'), 200, {}
        for i in range(3):
            pw_bytes = passwd.encode('utf-8')
            passwd = hashlib.sha512(pw_bytes + salt_bytes).hexdigest()
        db, cursor = pysql.database_connect()
        cursor.execute(
            '''UPDATE users SET password= %s, salt= %s WHERE login= %s''',
            (passwd, salt, login))
        db.commit()
        db.close()
        snippets = get_all_snipets()
        return render_template(
            'index.html',
            body=body,
            data=data,
            snippets=snippets,
            message='You successfully changed your password!'), 200, {}
    else:
        return render_template('passwordchange.html',
                               body=body,
                               data=data,
                               login=login,
                               message='Passwords are not match!'), 200, {}
Example #30
0
def main():
    num_words = int(input("Enter number of words >>> "))

    num_numbers = int(input("Enter number of numbers >>> "))

    num_special = int(input("Enter number of special characters >>> "))

    pass_str = create_password(num_words, num_numbers, num_special)

    # Testing strength of the password generated and giving feedback. Returned as tuple
    strength, feedback = test(pass_str)

    print("\nPassword: %s" % pass_str)
    print("\nStrength: %0.3f" % strength)
    print(
        'The closer to 0 the strength value, the stronger the password is.\n')
    print("\nFeedback: %s\n" % feedback)

    print("Feeling Adventurous (Y/N) ??? ")
    decision = input()

    if decision == 'y' or decision == 'Y':
        pass_str = elite(pass_str)
        print("\nPassword (1337): %s" % pass_str)
    def post(self, username):
        """
        A not-logged user is asking to register himself.
        NB: username must be a valid email address.
        """
        if not validate_email(username):
            return 'Error: username must be a valid email address!', HTTP_BAD_REQUEST

        password = request.form['password']
        if not password:
            return 'Error: the password mustn\'t be empty', HTTP_BAD_REQUEST

        strength, improvements = passwordmeter.test(password)
        if strength <= 0.5:
            return improvements, HTTP_FORBIDDEN
        activation_code = os.urandom(16).encode('hex')

        if username in userdata:
            # If an user is pending for activation, it can't be another one with the same name
            #  asking for registration
            return 'Error: username "{}" already exists!\n'.format(username), HTTP_CONFLICT

        # Composing email
        subject = '[{}] Confirm your email address'.format(__title__)
        sender = 'donotreply@{}.com'.format(__title__)
        recipients = [username]
        text_body_template = string.Template(_read_file(SIGNUP_EMAIL_TEMPLATE_FILE_PATH))
        values = dict(code=activation_code,
                      email=username,
                      appname=__title__,
                      )
        text_body = text_body_template.substitute(values)

        send_email(subject, sender, recipients, text_body)

        return create_user(username, password, activation_code)
Example #32
0
def is_strong_password(password):
    strength, improvements = test(password)
    if strength < 0.3:
        return False
    return True
 def test_default(self):
   res = pwm.test('password')
   self.assertEqual(len(res), 2)
   self.assertIsInstance(res[0], float)
   self.assertIsInstance(res[1], dict)
Example #34
0
novel = r.text

lines = novel.splitlines()
items = []
size = 16

for l in lines:
    line = l.strip()
    line = l.capitalize()
    line = ''.join(e for e in line if e.isalnum())
    if len(line) > size:
        items.append(line)

max = len(items)
# print(max)
# for idx, item in enumerate(items):
#     print("%d %s"%(idx, item))

randum = randint(0, max)
pwd = items[randum]
pwd = pwd[0:size]
print(pwd)
pwd = pwd + random_number_genertator(4) + random_special_chars_genertator(1)
print(pwd)

strength, improvements = passwordmeter.test(pwd)

print(strength)

for key, value in improvements.items():
    print(key, ":", value)
def test_Password(password):
    print("\n0 is not secure at all and 100 is extremely secure")
    print(test(password)[0] * 100)
Example #36
0

def print_password_strength(password_strength, verbose):
    password_grade, suggestions = password_strength
    password_grade = int(password_grade * 10)
    print("Strength of password is {:d}".format(password_grade))
    if verbose:
        if suggestions.values():
            print("Suggestions:")
            for suggestion in suggestions.values():
                print(suggestion)
        else:
            print("No suggestions")


def get_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='Prints suggestions for password.')
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    args = get_arguments()
    password = getpass.getpass()
    password_strength = passwordmeter.test(password)
    print_password_strength(password_strength, args.verbose)
 def test_default(self):
     res = pwm.test('password')
     self.assertEqual(len(res), 2)
     self.assertIsInstance(res[0], float)
     self.assertIsInstance(res[1], dict)
Example #38
0
    def put(self, username):
        """
        Activate user using activation code sent by email, or reset its password.
        """
        # create a list of all usernames with flag active: False

        # Pending users cleanup
        expired_pending_users = self._clean_inactive_users()
        logging.info('Expired pending users: {}'.format(expired_pending_users))

        if username in userdata:
            if userdata[username][USER_IS_ACTIVE] is True:
                # User active -> Password recovery/reset
                try:
                    new_password = request.form[PWD]
                except KeyError:
                    abort(HTTP_BAD_REQUEST)

                strength, improvements = passwordmeter.test(new_password)
                if strength <= 0.5:
                    return improvements, HTTP_FORBIDDEN

                request_recoverpass_code = request.form['recoverpass_code']
                recoverpass_stuff = userdata[username].get('recoverpass_data')

                if recoverpass_stuff:
                    recoverpass_code = recoverpass_stuff['recoverpass_code']
                    recoverpass_timestamp = recoverpass_stuff['timestamp']
                    if request_recoverpass_code == recoverpass_code and \
                            (now_timestamp() - recoverpass_timestamp < USER_RECOVERPASS_TIMEOUT):
                        userdata[username][PWD] = new_password
                        enc_pass = _encrypt_password(new_password)
                        userdata[username][PWD] = enc_pass
                        userdata[username].pop('recoverpass_data')
                        return 'Password changed succesfully', HTTP_OK
                # NB: old generated tokens are refused, but, currently, they are not removed from userdata.
                return 'Invalid code', HTTP_NOT_FOUND
            else:
                # User inactive -> activation
                activation_code = request.form['activation_code']
                logger.debug('Got activation code: {}'.format(activation_code))

                user_data = userdata[username]
                logger.debug('Creating user {}'.format(username))
                if activation_code == user_data[USER_CREATION_DATA][
                        'activation_code']:
                    # Actually activate user
                    encrypted_password = user_data[PWD]
                    return activate_user(username, encrypted_password)
                else:
                    abort(HTTP_NOT_FOUND)
        else:
            # Not-existing user --> 404 (OR create it in debug mode with a backdoor)
            #### DEBUG-MODE BACKDOOR ####
            # Shortcut to create an user skipping the email confirmation (valid in debug mode only!).
            if app.debug and activation_code == 'BACKDOOR':
                password = '******'
                logger.warn(
                    'WARNING: Creating user "{}" (password="******") '
                    'without email confirmation via backdoor!!!'.format(
                        username, password))
                return create_user(username, password, activation_code)
            #### DEBUG-MODE BACKDOOR ####

            return 'Error: username not found!\n', HTTP_NOT_FOUND
Example #39
0
def signup_db(headers, body, data):
    db, cursor = database_connect()
    login = str(data['name']) if 'name' in data else ''
    password = str(data['pw']) if 'pw' in data else ''
    password_conf = str(data['pwconf']) if 'pwconf' in data else ''
    answer = str(data['answer']) if 'answer' in data else ''

    cursor.execute('SELECT * FROM users WHERE login=%s', (login))
    questions_tuple = questions()
    if (cursor.fetchone()) is not None:
        return render_template(
            'signup.html',
            body=body,
            data=data,
            questions=questions_tuple,
            message='This login is already in use, please choose another one!'
        ), 200, {}
    if not check_login_char(login):
        return render_template(
            'signup.html',
            body=body,
            data=data,
            questions=questions_tuple,
            message='Login can only contains lowarcase letters!'), 200, {}
    if not check_login_length(login):
        return render_template('signup.html',
                               body=body,
                               data=data,
                               questions=questions_tuple,
                               message='Login is too long!'), 200, {}
    if not (password == password_conf):
        return render_template('signup.html',
                               body=body,
                               data=data,
                               questions=questions_tuple,
                               message='Passwords are not match!'), 200, {}
    strength, improvements = passwordmeter.test(password)

    if strength < 0.3:
        return render_template('signup.html',
                               body=body,
                               data=data,
                               questions=questions_tuple,
                               message='Your password is too weak!'), 200, {}
    create_user_folder(login)
    salt = uuid.uuid4().hex
    salt_bytes = salt.encode('utf-8')

    for i in range(3):
        answer_bytes = answer.encode('utf-8')
        pw_bytes = password.encode('utf-8')
        password = hashlib.sha512(pw_bytes + salt_bytes).hexdigest()
        answer = hashlib.sha512(answer_bytes + salt_bytes).hexdigest()
    cursor.execute(
        'INSERT INTO users(login, password, salt, answer) VALUES (%s, %s, %s, %s)',
        (login, password, salt, answer))
    db.commit()
    db.close()
    snippets = get_all_snipets()
    return render_template(
        'index.html',
        body=body,
        data=data,
        snippets=snippets,
        message='You successfully registered new user!'), 200, {}
Example #40
0
    print 'Downloading words.txt...'
    url='https://raw.githubusercontent.com/dwyl/english-words/master/words.txt'
    with open('words.txt', 'w') as f:
        f.write(urlopen(url).read())
        
words=open('words.txt', 'r').read().split("\n")
special_chars=['!','?']

def create_password(num_words=2,num_num,bers=4,num_special=1):
    pass_str=''
    
    for _ inxranf(num_words):
        passs_str=+choice(words).lower().capalize()
    for _ in xrange(num_numbers):
        pass_str+=str(randint(0,9))
    for _ in xrange(num_special):
        pass_str+=choice(speciam_chars)
        


def main();
    pass_str=create_password()
    strength,_=test(pass_str)

    print '\npassword: %s'%ss_str
    print 'Strength: %0.5f'%strength


if __name__='__main__':
        main()
    def put(self, username):
        """
        Activate user using activation code sent by email, or reset its password.
        """
        # create a list of all usernames with flag active: False

        # Pending users cleanup
        expired_pending_users = self._clean_inactive_users()
        logger.info('Expired pending users: {}'.format(expired_pending_users))

        if username in userdata:
            if userdata[username][USER_IS_ACTIVE] is True:
                # User active -> Password recovery/reset
                try:
                    new_password = request.form[PWD]
                except KeyError:
                    abort(HTTP_BAD_REQUEST)

                strength, improvements = passwordmeter.test(new_password)
                if strength <= 0.5:
                    return improvements, HTTP_FORBIDDEN

                request_recoverpass_code = request.form['recoverpass_code']
                recoverpass_stuff = userdata[username].get('recoverpass_data')

                if recoverpass_stuff:
                    recoverpass_code = recoverpass_stuff['recoverpass_code']
                    recoverpass_timestamp = recoverpass_stuff['timestamp']
                    if request_recoverpass_code == recoverpass_code and \
                            (now_timestamp() - recoverpass_timestamp < USER_RECOVERPASS_TIMEOUT):
                        userdata[username][PWD] = new_password
                        enc_pass = _encrypt_password(new_password)
                        userdata[username][PWD] = enc_pass
                        userdata[username].pop('recoverpass_data')
                        return 'Password changed succesfully', HTTP_OK
                # NB: old generated tokens are refused, but, currently, they are not removed from userdata.
                return 'Invalid code', HTTP_NOT_FOUND
            else:
                # User inactive -> activation
                activation_code = request.form['activation_code']
                logger.debug('Got activation code: {}'.format(activation_code))

                user_data = userdata[username]
                logger.debug('Creating user {}'.format(username))
                if activation_code == user_data[USER_CREATION_DATA]['activation_code']:
                    # Actually activate user
                    encrypted_password = user_data[PWD]
                    return activate_user(username, encrypted_password)
                else:
                    abort(HTTP_NOT_FOUND)
        else:
            # Not-existing user --> 404 (OR create it in debug mode with a backdoor)
            #### DEBUG-MODE BACKDOOR ####
            # Shortcut to create an user skipping the email confirmation (valid in debug mode only!).
            if app.debug and activation_code == 'BACKDOOR':
                password = '******'
                logger.warn('WARNING: Creating user "{}" (password="******") '
                             'without email confirmation via backdoor!!!'.format(username, password))
                return create_user(username, password, activation_code)
            #### DEBUG-MODE BACKDOOR ####

            return 'Error: username not found!\n', HTTP_NOT_FOUND
Example #42
0
def main():
    pass_str = create_password()
    strength, _ = test(pass_str)
    print("\nPassword: %s" % pass_str)
    print("Strength: %0.5f" % strength)