Search code examples
pythonstringxorbitdes

Xor bits in python


Well I have an assignment to implement DES and I chose python, only problem is I can't figure out how to XOR bits of a String or Byte String, I can manually XOR them if only I can manage to read the 1s and 0s in them.

Example:

s1 = b'abc'
s2 = b'efg'

s3 = XOR(s1,s2) // my own method

How can I XOR them or how can I get the binary values of 1s and 0s that represent them?

If you use any python methods explain them, I'm relatively new to this language.


Solution

  • First you need to zip your strings then use ord (in python 2) and ^ for each of characters :

    >>> s1 = b'abc'
    >>> s2 = b'efg'
    >>> ''.join(chr(ord(i)^ord(j)) for i,j in zip(s1,s2))
    '\x04\x04\x04'
    

    the ord() function retuen value of the byte when the argument is an 8-bit string.But if you are using python 3 you dont need ord :

    >>> ''.join(chr(i^j) for i,j in zip(s1,s2))
    '\x04\x04\x04'
    

    Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)

    example :
    
    >>> s1[0]
    97
    >>> s1[0:1]
    b'a'
    

    and if you want to convert back your strings you need to firs convert the XORed string to binary you can do it by binascii.a2b_qp function :

    >>> import binascii 
    >>> s=''.join(chr(i^j) for i,j in zip(s1,s2))
    >>> s4=binascii.a2b_qp(s)
    >>> ''.join(chr(i^j) for i,j in zip(s1,s4))
    'efg'