pythonbit-manipulationfuzz-testing

Randomly flipping bits in a python binary string


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?


Solution

  • 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)