Link Search Menu Expand Document

Break password with brute force

In this section, we will write a function that can break passwords by brute-force testing all possible combinations.

In c, we define all the possible characters we will use. We use only lowercase letters and numbers to simplify the process. The more possible characters, such as uppercase letters or special characters like ?-.,, the more complex it becomes to break the password.

The algorithm is straightforward and tests combinations from length 1 to long_max. Here are some examples of the combinations tested:

  • For length 1, it tests: a, b, c, … up to 9.
  • For length 2, it tests: aa, ab, ac, … 9a, 9b, … up to 99.
  • For length 3, it tests: aaa, aab, … 9aa, 9aab, … up to 999.

As you can see, the number of combinations grows exponentially. The more characters and the longer the length, the harder it is to break.

import itertools

def brute_force(password, long_max=6):
    c = "abcdefghijklmnopqrstuvwxyz0123456789"
    
    for length in range(1, long_max + 1):
        print(f"Length {length}...")
        for attempt in itertools.product(c, repeat=length):
            attempt_s = ''.join(attempt)
            if attempt_s == password:
                return attempt_s
    return None

If our password consists only of letters and numbers and is of length 6, you can see how we can break it in a few seconds.

password = "pass67"
found = brute_force(password, long_max=8)
print(f"Password found: {found}")

✏️ Exercises:

  • Calculate the possible combinations for a password with numbers and letters of length 10. Try to break it with brute force.