Frage

I'm creating some fuzz tests in python and it would be invaluable for me to be able to, given a binary string, randomly flip some bits and ensure that exceptions are correctly raised, or results are correctly displayed for slight alterations on given valid binaries. Does anyone know how I might go about this in Python? I realize this is pretty trivial in lower level languages but for work reasons I've been told to do this in Python, but I'm not sure how to start this, or get the binary representation for something in python. Any ideas on how to execute these fuzz tests in Python?

War es hilfreich?

Lösung

Strings are immutable, so to make changes, the first thing to do is probably to convert it into a list. At the same time, you can convert the digits into ints for greater ease in manipulation.

hexstring = "1234567890deadbeef"
values = [int(digit, 16) for digit in hexstring]

Then you can flip an individual bit in any of the hex digits.

digitindex = 2
bitindex = 3
values[digitindex] ^= 1 << bitindex

If needed, you can then convert back to hex.

result = "".join("0123456789abcdef"[val] for val in values)

Andere Tipps

One thing you could try is to convert the string into a bytearray, then performing bit manipulations on each character. You can access each character by index and treat it as an integer.

For example:

>>> a = "hello world"
>>> b = bytearray(a)
>>> b[0] = b[0] ^ 5    # bitwise XOR
>>> print b            # or do str(b) to convert it back to a string
mello world

You may also find this article on the Python wiki about bit manipulation to be useful. It goes over bit manipulation in Python to far greater detail, along with loads of useful tips and tricks.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top