Looping through an 8-byte hex code in python
<p>I have an 8-byte hex code and i'm trying to loop through 00-FF for each byte starting from the last to the first but i'm new to python and i'm stuck. </p>

<p>here's the code for looping through 00-FF:</p>

<pre><code>for h in range(0, 256):
    return "{:02x}".format(h) 
</code></pre>

<p>Essentially what i have is a </p>

<pre><code>hexcode = 'f20bdba6ff29eed7'
</code></pre>

<p>EDIT: I'm going to add a little background information on this and remove my previous explanation. I'm writing a Padding Attack aglorithm with DES. Here's what needs to happen:</p>

<pre><code>hexcode = 'f20bdba6ff29eed7'
for i in range(0,8):
    (FOR i = 0 ) Loop through 00-FF for the last byte (i.e. 'd7') until you find the value that works
    (FOR i = 1 ) Loop through 00-FF for the 7th byte (i.e. 'ee') until you find the value that works
    and so on until the 1st byte
</code></pre>

<p>MY PROBLEM: my problem is that i dont know how to loop through all 8 bytes of the hex. This is easy when it's the 8th byte, because i just remove the last two elements and loop through 00-FF and add it back to hex to see if its the correct code. Essentially what the code does is :</p>

<pre><code>remove last two elements of hex
try 00 as the last two elements
if the test returns true then stop
if it doesn't move to 01 (cont. through FF, but stop when you find the correct value)
</code></pre>

<p>My issue is, when its the bytes in the middle (2-7) how do i loop for a middle value and then add it all back together. Essentially</p>

<pre><code>For byte 7:
Remove elements 13,14 from hex
try 00 as element 13,14
add hex[0:12] + 00 + hex [15:16]
if 00 returns true then stop, if not then loop through 01-ff until it does
</code></pre>

<p>and so on for bytes 6,5,4,3,2,1</p>

<p>Here's a quick way to break a string into chunks. We assume it has even length.</p>

<pre><code>hexcode = 'f20bdba6ff29eed7'
l = len(hexcode)
for n in range(0, len(hexcode)/2):
    index = n * 2
    print hexcode[index:index+2]
</code></pre>

<p>If you need to operate on the string representations, you could easily generate a list of two character bytecodes using something similar to this. Personally, I prefer to operate on the bytes, and use the hexcodes only for IO.</p>

<pre><code>[hexcode[n*2:n*2+2] for n in range(len(hexcode)/2)]
</code></pre>

python loops hex