w3resource

Python Cyber Security - Generate password from a dictionary file


Write a Python program that generates a password using a random combination of words from a dictionary file.

Content of the dictionary file (dictionary.txt) :

Pas1$Ku1
password
password123
password123$
Password6#(%
Germany#12
USA12^$#
England0#

Sample Solution:

Python Code:

import random

def generate_password():
    # Open dictionary file
    with open('dictionary.txt') as f:
        words = f.read().splitlines()
    
    # Randomly select four words
    password = random.sample(words, 4)
    
    # Combine words with hyphens
    password = '-'.join(password)
    
    return password

# Example usage
password = generate_password()
print(password)

Sample Output:

USA12^$#-password123-England0#-password123$
password-England0#-Password6#(%-Pas1$Ku1
USA12^$#-password123-password123$-password 

Explanation:

In the above exercise, we first open a dictionary file and read all the words. Then, we use the random.sample() function to randomly select four words from the list of words. Finally, we combine the words with hyphens to form the final password. You can adjust the number of words included in the password by changing the argument to random.sample().

Flowchart:

Flowchart: Check if passwords in a list have been leaked in data breaches

Python Code Editor:

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

Previous: Check password strength and get suggestions.
Next: Program for simulating dictionary attack on password.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.