loop through all possible combination of 8 bytes

Question:

I want to do something like this:

for i in range('xff'*8):
  hash = b'challenge' + i
  inp = hashlib.sha256(hash).digest()

I don’t know how i can get all the possible combinations of 8 bytes with bitwise operations.

Asked By: haruhi

||

Answers:

You can do this, but using struct would be preferred, I’ve also added the zero check (increase 2 to 26…):

start = b'' * 2
import hashlib
for i in range(256 ** 8):
    byte = b'challenge' + bytes.fromhex("%016x" % i)
    inp = hashlib.sha256(byte).digest()
    if inp.startswith(start):
        print(byte, inp)
        break

Output:

b'challengex00x00x00x00x00x00*xde' b'x00x00x9ax84Hxbcx07xd7xdcx07#xb8x08Axb1&xdcDxb0 x84\9y#xc9xcfxaaxffxb7xbfx9a'
...

I mean you’re already using hashlib, so you could as well use another standard library:

start = b'' * 2
import hashlib, struct
for i in range(256 ** 8):
    byte = b'challenge' + struct.pack(">Q", i)
    inp = hashlib.sha256(byte).digest()
    if inp.startswith(start):
        print(byte, inp)
        break
Answered By: Nineteendo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.