Day 26: Password Generator

Objective

Create a program that generates random, secure passwords based on user-defined criteria, such as:

  1. Length of the password.
  2. Whether to include uppercase letters, lowercase letters, numbers, and special characters.

For example:

  • Input: Length = 12, include numbers and special characters.
  • Output: “A9!k2#Pq8&Lm”

Why This Challenge Is Important

Password security is a fundamental part of technology today. This challenge teaches:

  • Randomization to generate unpredictable passwords.
  • Using character sets to meet specific user requirements.
  • Writing reusable and flexible code that accommodates user preferences.

Steps to Solve

1. Understand the Problem

Your program should:

  • Ask the user how long the password should be.
  • Prompt the user to include or exclude uppercase letters, lowercase letters, numbers, and special characters.
  • Generate a random password based on the selected criteria.

2. Plan Your Solution

  1. Define character sets:
    • Uppercase letters: A–Z
    • Lowercase letters: a–z
    • Numbers: 0–9
    • Special characters: !@#$%^&*()-_=+[]{};:,.<>?/
  2. Take user input for password length and character preferences.
  3. Combine the chosen character sets and randomly select characters to create the password.
  4. Ensure the password meets the user’s requirements (e.g., includes at least one character from each chosen category).

Code Examples

Python Example

import random

def generate_password(length, use_uppercase, use_lowercase, use_numbers, use_special):
    # Define character sets
    uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    lowercase = "abcdefghijklmnopqrstuvwxyz"
    numbers = "0123456789"
    special = "!@#$%^&*()-_=+[]{};:,.<>?/"

    # Build the pool of characters based on user input
    pool = ""
    if use_uppercase:
        pool += uppercase
    if use_lowercase:
        pool += lowercase
    if use_numbers:
        pool += numbers
    if use_special:
        pool += special

    if not pool:
        return "Error: No character types selected."

    # Generate the password
    password = "".join(random.choice(pool) for _ in range(length))
    return password

# Get user preferences
print("Welcome to the Password Generator!")
length = int(input("Enter the desired password length: "))
use_uppercase = input("Include uppercase letters? (yes/no): ").lower() == "yes"
use_lowercase = input("Include lowercase letters? (yes/no): ").lower() == "yes"
use_numbers = input("Include numbers? (yes/no): ").lower() == "yes"
use_special = input("Include special characters? (yes/no): ").lower() == "yes"

# Generate and display the password
password = generate_password(length, use_uppercase, use_lowercase, use_numbers, use_special)
print("Your generated password is:", password)

Java Example

import java.util.Random;
import java.util.Scanner;

public class PasswordGenerator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        // Character sets
        String uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lowercase = "abcdefghijklmnopqrstuvwxyz";
        String numbers = "0123456789";
        String special = "!@#$%^&*()-_=+[]{};:,.<>?/";

        // Get user preferences
        System.out.println("Welcome to the Password Generator!");
        System.out.print("Enter the desired password length: ");
        int length = scanner.nextInt();
        System.out.print("Include uppercase letters? (yes/no): ");
        boolean useUppercase = scanner.next().equalsIgnoreCase("yes");
        System.out.print("Include lowercase letters? (yes/no): ");
        boolean useLowercase = scanner.next().equalsIgnoreCase("yes");
        System.out.print("Include numbers? (yes/no): ");
        boolean useNumbers = scanner.next().equalsIgnoreCase("yes");
        System.out.print("Include special characters? (yes/no): ");
        boolean useSpecial = scanner.next().equalsIgnoreCase("yes");

        // Build the pool of characters
        String pool = "";
        if (useUppercase) pool += uppercase;
        if (useLowercase) pool += lowercase;
        if (useNumbers) pool += numbers;
        if (useSpecial) pool += special;

        if (pool.isEmpty()) {
            System.out.println("Error: No character types selected.");
            return;
        }

        // Generate the password
        StringBuilder password = new StringBuilder();
        for (int i = 0; i < length; i++) {
            password.append(pool.charAt(random.nextInt(pool.length())));
        }

        System.out.println("Your generated password is: " + password.toString());
    }
}

JavaScript Example

function generatePassword(length, useUppercase, useLowercase, useNumbers, useSpecial) {
    const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const lowercase = "abcdefghijklmnopqrstuvwxyz";
    const numbers = "0123456789";
    const special = "!@#$%^&*()-_=+[]{};:,.<>?/";

    let pool = "";
    if (useUppercase) pool += uppercase;
    if (useLowercase) pool += lowercase;
    if (useNumbers) pool += numbers;
    if (useSpecial) pool += special;

    if (pool === "") {
        return "Error: No character types selected.";
    }

    let password = "";
    for (let i = 0; i < length; i++) {
        password += pool[Math.floor(Math.random() * pool.length)];
    }

    return password;
}

// Get user input
console.log("Welcome to the Password Generator!");
const length = parseInt(prompt("Enter the desired password length:"));
const useUppercase = confirm("Include uppercase letters?");
const useLowercase = confirm("Include lowercase letters?");
const useNumbers = confirm("Include numbers?");
const useSpecial = confirm("Include special characters?");

// Generate and display the password
const password = generatePassword(length, useUppercase, useLowercase, useNumbers, useSpecial);
console.log("Your generated password is:", password);

Edge Cases to Consider

  1. Zero Length Password: Ensure the user doesn’t enter 0 for the password length.
  2. No Character Types: Handle cases where the user doesn’t select any character types.
  3. Extreme Length: Warn the user if the password length is excessively large.

Extensions to Explore

  1. Avoid Similar Characters: Remove confusing characters like 0, O, l, and 1 for easier readability.
  2. Customizable Exclusions: Allow users to exclude specific characters from the password.
  3. Multiple Passwords: Generate a list of multiple passwords for the user to choose from.
  4. Password Strength Checker: Include feedback on the strength of the generated password.

What You’ve Learned

  • How to use randomization to generate secure passwords.
  • Handling user preferences to build flexible programs.
  • Combining and working with strings effectively.

Next Steps

In Day 27: Text-Based Adventure Game, you create an interactive text-based adventure game where the user navigates through a story by making choices.