w3resource

Python Cyber Security - Function to suggest character substitutions for stronger passwords

Python Cyber Security: Exercise-4 with Solution

Write a Python function that takes a password as input and returns a list of common character substitutions that could be used to create a stronger password.

For example, if the password is "myspass", the function should return

['my$pass', 'my5pass', 'mySpass', 'mysp@ss', 'mysp4ss', 'myspAss', 'myspa$s', 'myspa5s', 'myspaSs', 'myspas$', 'myspas5', 'myspasS', 'myspass!', 'myspass123', 'myspass@', 'myspass#', 'myspass$', 'myspass%', 'myspass&', 'myspass*', 'myspass-', 'myspass_', 'myspass=', 'myspass+']

Sample Solution:

Python Code:

def get_password_variants(password):
    pass_variants = []
    substitutions = {
        'a': ['@', '4', 'A'],
        'e': ['3', 'E'],
        'i': ['1', '!', 'I'],
        'o': ['0', 'O'],
        's': ['$', '5', 'S'],
        't': ['7', 'T'],
        'z': ['2', 'Z']
    }
    
    for i in range(len(password)):
        if password[i] in substitutions:
            for sub in substitutions[password[i]]:
                pass_variant = password[:i] + sub + password[i+1:]
                pass_variants.append(pass_variant)
    
    pass_variants.append(password + '!')
    pass_variants.append(password + '123')
    pass_variants.append(password + '@')
    pass_variants.append(password + '#')
    pass_variants.append(password + '$')
    pass_variants.append(password + '%')
    pass_variants.append(password + '&')
    pass_variants.append(password + '*')
    pass_variants.append(password + '-')
    pass_variants.append(password + '_')
    pass_variants.append(password + '=')
    pass_variants.append(password + '+')    
    return pass_variants
password = input("Input your password: ")
result_variants = get_password_variants(password)
print(result_variants)

Sample Output:

Input your password:  pqre3sd
['pqr33sd', 'pqrE3sd', 'pqre3$d', 'pqre35d', 'pqre3Sd', 'pqre3sd!', 'pqre3sd123', 'pqre3sd@', 'pqre3sd#', 'pqre3sd$', 'pqre3sd%', 'pqre3sd&', 'pqre3sd*', 'pqre3sd-', 'pqre3sd_', 'pqre3sd=', 'pqre3sd+']

Flowchart:

Flowchart: Hash Password String using SHA-256 Algorithm

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Check password strength.
Next: Check and print valid passwords from a file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/cybersecurity/python-cybersecurity-exercise-4.php