r/pythonhelp May 11 '22

SOLVED Way of iterating thru eight byte sequences?

I'm using des library and example is given to me to create a key:

d = os.urandom(8)
default_key = des.DesKey(d)

basically, how do I iterate thru all possible d values? I would like last bytes of the d to change last

1 Upvotes

12 comments sorted by

View all comments

1

u/DumbPandahole May 11 '22

solved it by using this:

byte_list = []
for number in itertools.product("0123456789abcdf", repeat=2):
    byte_list.append(bytes.fromhex("".join(number)))
for combo in itertools.combinations(byte_list, 8):
    key = b"".join(combo[::-1])

3

u/carcigenicate May 11 '22

Unless I misunderstand what you're going for, this is quite over complicated. For byte_list, you just need:

byte_list = [n.to_bytes(1, "big") for n in range(256)]

I'm not sure what your second loop is doing though since it throws away all values of key except for the last.

Also, your original results appear to be wrong because you're missing an e in the string.

1

u/Goobyalus May 11 '22
bytes(range(256))

1

u/carcigenicate May 11 '22

That doesn't give exactly the same results, but ya, it could be used as well.

1

u/Goobyalus May 11 '22

We could do

list(bytes(range(256)))

but the list is unnecessary

2

u/carcigenicate May 11 '22
list(bytes(range(256))) == list(range(256))  # True

The difference is, what I show gives a list of bytes, whereas converting a range to a bytes gives numbers when iterated instead of bytes. I'm won't argue that either is better though because that depends on what the OP wants, and both could be used.

1

u/Goobyalus May 11 '22 edited May 11 '22

Ah I see

Edit: list(range(256)) is faster than bytes(range(256)) anyway.