Home Python - Loop stops running after a short while
Reply: 1

Python - Loop stops running after a short while

shdewzi
1#
shdewzi Published in 2018-01-12 20:14:34Z

So here I'm generating random hex values, hashing them and comparing to a pre-given hash. The program tests about 4 000 hashes and then just stops running without an error.

Here's the loop part of the code:

def loop():

    randomhex = binascii.b2a_hex(os.urandom(4))
    hash_object = hashlib.sha1(randomhex)
    hashh = hash_object.hexdigest()
    print(hashh)

    if hashh == sha:
        done()
    else:
        loop()
Jean-François Fabre
2#
Jean-François Fabre Reply to 2018-01-12 20:39:10Z

you cannot use recursion for a loop like this

Here's a small view of your call tree:

loop()
  loop()
    loop()
      loop()
        loop()
          loop()
             ...

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:

def loop():

  while True:
    randomhex = binascii.b2a_hex(os.urandom(4))
    hash_object = hashlib.sha1(randomhex)
    hashh = hash_object.hexdigest()
    print(hashh)

    if hashh == sha:
        # we found the result: exit the loop
        break

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308724 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO