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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
HonorGodSoftware EngineerCommented:
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

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

HonorGodSoftware EngineerCommented:
Thanks for the assist, and the points.

Good luck & have a great day.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.