Scoob
Scoob

Reputation: 551

How do I loop through every possible value of a byte in python?

I am conducting a Padding Oracle Attack for my Information Security course. Without getting into the details of the attack, I need to have a for loop that loops through all possible 1 byte hex values.

Pseudo-code of what I need to do:

for x in range('\x00', '\xFF'):
    replace last byte of ciphertext with byte
    perform padding check

I cannot figure out how to accomplish this. Any ideas?

Upvotes: 1

Views: 3641

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122292

Bytes are really just integers in the range 0-255 (inclusive), or in hex, 0 through to FF. Generate the integer, then create the byte value from that. The bytes() type takes a list of integers, so create a list of length 1:

for i in range(0xff):
    b = bytes([i])

If you store the ciphertext in a bytearray() object, you could even trivially replace that last byte by using the integer directly:

ciphertext_mutable = bytearray(ciphertext)
for i in range(0xff):
    ciphertext_mutable[-1] = i  # replace last byte

Upvotes: 3

Related Questions