Python Forum
Code starts slowing down? MemoryError
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code starts slowing down? MemoryError
#1
(Information before reading: I am a native German speaker and i learned English in school, so i am sorry if something sounds incomprehensible)

Hello there,

i created a brute force program. At first i want to explain how it works. When you start that program, you have to choose a hash algorithm and then put in the hash. Then you have to choose a number for min chars and max chars that the plain password could have. My main problem is that if i choose a password with for example 5 characters and hash that using sha512 or something else and try to brute force that password using my program, the program easily runs through 3 and 4 char passwords, but when it starts to go through all possible 5 char passwords it starts hanging. Normally the progress bar in the console should display how many percent of all possible passwords were tried to compare but it takes very long time to get started with this process.

BTW: If you have any improvements to my code, let me please know because i am learning python and it would be grateful!

Preview (3 min):


Error detected while running:
Error:
Traceback (most recent call last): File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 122, in <module> main() File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 116, in main bruteforce(min, max, hash, hashfunction) File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 91, in bruteforce if bf_sha512(_, hash) is not None: File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 23, in bf_sha512 passwords = [functools.reduce(operator.add, (p)) for p in itertools.product(chars, repeat=n)] File "C:/Users/ashka/PycharmProjects/bruteforce/main.py", line 23, in <listcomp> passwords = [functools.reduce(operator.add, (p)) for p in itertools.product(chars, repeat=n)] MemoryError Process finished with exit code 1
Code:
# Just importing modules
import itertools
import functools
import operator
import hashlib
import time
from tqdm import tqdm, trange

# Defining the string with all useable characters for a password (excluded special character)
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

# Available hashfunctions
hashfunctions = ['sha512', 'sha256', 'md5']


# Function for SHA512
def bf_sha512(n, hash):
    max_counts = int(chars.__len__())**n
    print(' ')
    print('Testing all possible passwords with ' + str(n) + ' characters... [' + str(max_counts) + ']')
    with tqdm(total=max_counts) as pbar:
        count = 0
        passwords = [functools.reduce(operator.add, (p)) for p in itertools.product(chars, repeat=n)]
        for password in passwords:
            count = count + 1
            pbar.update(1)
            if hashlib.sha512(password.encode()).hexdigest() == hash:
                print('Needed attempts: ' + str(count))
                print(' ')
                print("Hash: " + hash)
                print("Passwort: " + password)
                pbar.close()
                return password
        pbar.close()
        return None


# Function for SHA256
def bf_sha256(n, hash):
    max_counts = int(chars.__len__())**n
    print(' ')
    print('Testing all possible passwords with ' + str(n) + ' characters... [' + str(max_counts) + ']')
    with tqdm(total=max_counts) as pbar:
        count = 0
        passwords = [functools.reduce(operator.add, (p)) for p in itertools.product(chars, repeat=n)]
        for password in passwords:
            count = count + 1
            pbar.update(1)
            if hashlib.sha256(password.encode()).hexdigest() == hash:
                print('Needed attempts: ' + str(count))
                print(' ')
                print("Hash: " + hash)
                print("Passwort: " + password)
                pbar.close()
                return password
        pbar.close()
        return None


# Function for MD5
def bf_md5(n, hash):
    max_counts = int(chars.__len__())**n
    print(' ')
    print('Testing all possible passwords with ' + str(n) + ' characters... [' + str(max_counts) + ']')
    with tqdm(total=max_counts) as pbar:
        count = 0
        passwords = [functools.reduce(operator.add, (p)) for p in itertools.product(chars, repeat=n)]
        for password in passwords:
            count = count + 1
            pbar.update(1)
            if hashlib.md5(password.encode()).hexdigest() == hash:
                print('Needed attempts: ' + str(count))
                print(' ')
                print("Hash: " + hash)
                print("Passwort: " + password)
                pbar.close()
                return password
        pbar.close()
        return None


# Function for detecting hash algorithm and choosing the right function to decrypt
def bruteforce(min, max, hash, hashfunction):
    print('Working... Do not exit!')
    print(' ')
    starttime = time.time()
    max_counts = int(chars.__len__())**int(max)
    print(f'Max possible password combinations: {max_counts:,d}')
    for _ in range(int(min), int(max) + 1):
        if hashfunction == 'sha512':
            if bf_sha512(_, hash) is not None:
                break
        elif hashfunction == 'sha256':
            if bf_sha256(_, hash) is not None:
                break
        elif hashfunction == 'md5':
            if bf_md5(_, hash) is not None:
                break
    endtime = time.time()
    executiontime = endtime - starttime
    print("Execution Time: " + str(executiontime) + " sec")


# Main function
def main():
    print("Python Bruteforce v1.0")
    print(' ')
    print('Used pattern: ' + chars)
    print('Hashfunctions: sha512, sha256, md5')
    hashfunction = input('Hashfunction: ')
    if hashfunction in hashfunctions:
        hash = input('Enter ' + hashfunction + ' hash: ')
        min = input('Enter min password length: ')
        max = input('Enter max password length: ')
        print(' ')
        bruteforce(min, max, hash, hashfunction)
    else:
        print('Please select an given hashfunction!')


if __name__ == '__main__':
    main()
Reply
#2
Problem solved!

For those who get the same error, here is the answer:
the problem in the line that causes this error is the transformation from a generator (a piece of code that yields one result at a time until it finishes running) that is very memory-efficient, to a list by using [] around
functools.reduce(operator.add, p) for p in itertools.product(chars, repeat=n)
.
by converting it into a list you make the generator output all its values into a list, which cannot contain more than 536,870,912 items on 32bit machines. when the list gets bigger than that you get the memory error.

solution: remove the []
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  MemoryError in pywinauto.findwindows.find_windows – Need Help! ktw3857 0 195 Mar-25-2024, 02:23 AM
Last Post: ktw3857
  Problem with my code slowing down and crashing SuchUmami 1 504 Jul-21-2023, 10:09 AM
Last Post: Gribouillis
  Move column to the right if it starts with a letter mfernandes 0 671 Oct-25-2022, 11:22 AM
Last Post: mfernandes
  Setup Portable Python on Windows for script starts with double clicks? pstein 0 1,806 Feb-18-2022, 01:29 PM
Last Post: pstein
  Regex: a string does not starts and ends with the same character Melcu54 5 2,401 Jul-04-2021, 07:51 PM
Last Post: Melcu54
  Run a timer when a functions starts to see how long the function takes to complete Pedroski55 2 1,993 Apr-19-2020, 06:28 AM
Last Post: Pedroski55
  Getting MemoryError frames.write(buffer) kunwarsingh 0 1,600 Feb-10-2020, 09:39 PM
Last Post: kunwarsingh
  sensor code that starts heater chano 3 3,130 Jun-05-2019, 10:54 AM
Last Post: michalmonday
  MemoryError AwaAgathe 0 1,726 Feb-26-2019, 02:57 AM
Last Post: AwaAgathe
  MemoryError mitmoot 5 3,807 Dec-07-2018, 04:53 PM
Last Post: mitmoot

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020