you cannot use recursion for a loop like this
Here's a small view of your call tree:
and so on until stack exhaustion...
- you don't need recursion, you're not using previous results at all, you don't need backtracking, you don't have a base case...
- while it could work if you're lucky, most of the time after a lot of iterations/recursive calls, you're reaching the max recursion limit and the program crashes, when a simple
while loop is enough.
Personally I prefer a
while True loop with a manual
break, which saves the hassle to initialize variables before the loop, like this:
randomhex = binascii.b2a_hex(os.urandom(4))
hash_object = hashlib.sha1(randomhex)
hashh = hash_object.hexdigest()
if hashh == sha:
# we found the result: exit the loop
As a side note, using bruteforce and random together isn't a very efficient way to break a hash... Even if the chances of repeat are very thin with
os.urandom a simple loop from 1 to 2**31 would be faster to compute.