2
\$\begingroup\$

I've made a python program that can brute-force both MD5 and SHA1 hashes, and I would like know if I could make the program faster or any way I could improve it. I'm still a beginner in python and in coding in general (this program is only for learning purposes).

The code:

import time
import string
import hashlib
ready = False
start = time.time()
chars = list(string.printable)[:95]
base = len(chars)
n = 0
hashmethod = 0
password = ""
solved = False
quit = ""
while ready != True:
    password = input("Enter a valid MD5 or SHA-1 hash:")

if len(password) == 32:
    ready = True
elif len(password) == 40:
    ready = True
    hashmethod = 2
else:
    continue


def numberToBase(n, b):  # converts number N base 10 to a list of digits base b
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]


# check edge cases like empty, or 0
if password == '':
    print('Your password is empty')
    solved = True

# begin systematically checking passwords
while not solved:
    lst = numberToBase(n, base)
    word = ''
    for x in lst:
        word += str(chars[x])
    if hashmethod == 2:
        hashedGuess = hashlib.sha1(bytes(word, 'utf-8')).hexdigest()

    else:
        hashedGuess = hashlib.md5(bytes(word, 'utf-8')).hexdigest()
        print(word)
    if password == hashedGuess:
        solved = True
        print('-Stats-')
        print('Pass: ' + word)
        print('Attempts: ' + str(n))
        print('time: ' + str((time.time() - start)) + ' sec')
        while quit != " QUIT":
            quit = input('Type <QUIT> to quit')
    else:
        n += 1
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

For hash brute-forcing, the short answer is "don't do it in Python". You'll get massive performance gains in switching to C or C++.

Since this is for learning purposes, reviewing your Python:

  • For legibility, add a newline between your imports and your code.
  • Consider putting your global-scope code into a main() function plus subdividing some of the code into other functions.
  • Does your code actually run? You have a loop on ready, but you don't modify its value, so I think it's going to hang there. I suspect that you've broken your loop's indentation, and that some statements below belong in the loop.
  • Instead of setting ready to later break out of the loop, you can simply break. You can get rid of your else/continue.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.