XOR decrypt example in Python.

I'm kinda new to Python, and I have a task to decrypt a socket stream that has been XOR'd.  I wondered if someone could provide a clear example or walk me through the process in outline form if not code.  I can connect to the stream just fine and print each byte, but I can't get the decrypt.  I do have the proper key -- just don't know how to use it.  The online examples I've looked at are roughly a page of script and include a lot of unrelated XOR stuff, so I've had a hard time picking up on the process / core concept.
Who is Participating?
peprConnect With a Mentor Commented:
The ^ is the bitwise xor operator. Try the following (here in the interactive Python Shell):

>>> a = 255
>>> hex(a)
>>> b = a ^ 255
>>> b
>>> c = a ^ 0x0f
>>> c
>>> hex(c)
HonorGodConnect With a Mentor Commented:
You may have to remember to break the input message into pieces, or chunks that are the same length as your key.

For example, if your key is 4 bytes (32 bits) long, you want your message to be broken into 4 byte / character pieces, and XOR each piece.  One of the questions you have to consider though is:

What happens at the end of the message.  What if it is > 0, and < 4 bytes long?

Can / will your code handle it well?

Good luck
ammasajanConnect With a Mentor Commented:

Please try this example; code documentation will guide you through the xor encryption and decryption.

I hope I answered your query with a simple example!

class PEcrypt:
    PEcrypt - very, very simple word key encryption system
              uses cyclic XOR between the keyword character
              bytes and the string to be encrypted/decrypted.
              Therefore, the same function and keyword will
              encrypt the string the first time and decrypt
              it if called on the encrypted string.

    def __init__(self, aKey):
        Initialise the class with the key that
        is used to encrypt/decrypt strings
        self.key = aKey

        # CRC can be used to validate a key (very roughly)
        # if you store the CRC from a previous keyword
        # and then compare with a newly generated one and
        # they are the same then chances are the keyword
        # is correct - only a single byte so not that reliable
        self.crc = 0    
        for x in self.key:
            intX = ord(x)
            self.crc = self.crc ^ intX

    def Crypt(self, aString):
        Encrypt/Decrypt the passed string object and return
        the encrypted string
        kIdx = 0
        cryptStr = ""   # empty 'crypted string to be returned

        # loop through the string and XOR each byte with the keyword
        # to get the 'crypted byte. Add the 'crypted byte to the
        # 'crypted string
        for x in range(len(aString)):
            cryptStr = cryptStr + \
                       chr( ord(aString[x]) ^ ord(self.key[kIdx]))
            # use the mod operator - % - to cyclically loop through
            # the keyword
            kIdx = (kIdx + 1) % len(self.key)

        return cryptStr

if __name__ == "__main__":

    def strToHex(aString):
        hexStr = ""
        for x in aString:
            hexStr = hexStr + "%02X " % ord(x)

        return hexStr
    # self test routine

    print "\nTesting PEcrypt!"
    print "----------------\n"

    keyStr = "klsdjfkl23"
    testStr = "Hello from Saj."

    print "\nString : ", testStr
    print "in hex : ", strToHex(testStr)
    print "key    : ", keyStr

    pe = PEcrypt(keyStr)  # generate the PEcrypt instance
    print "\nPEcrypt CRC = %02X" % pe.crc

    testStr = pe.Crypt(testStr)
    print "\nEncrypted string"
    print "Ascii  : ", testStr
    print "Hex    : ", strToHex(testStr)

    testStr = pe.Crypt(testStr)
    print "\nDecrypted string"
    print "Ascii  : ", testStr
    print "Hex    : ", strToHex(testStr)

Open in new window

Thanks for the assist, and the points.

Good luck & have a great day.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.