XOR crypt a printable text (Python)

vegaseat 2 Tallied Votes 341 Views Share

The normal XOR crypting is used with a small base64 twist to produce printable crypted text.

# If you send a normal text to this xor_crypter, it will return
# a base64 encoded printable crypted string.
# To get the text back, send the base64 string through again.
# tested with Python24   by      vegaseat     17apr2007

import operator
import StringIO
import base64

def xor_crypt(str1, pw):
    if str1.endswith("="):
        str2 = base64.b64decode(str1)
    else:
        str2 = str1
    # create two streams in memory the size of the string str2
    # one stream to read from and the other to write XOR crypted character to
    sr = StringIO.StringIO(str2)
    sw = StringIO.StringIO(str2)
    # make sure we start both streams at position zero (beginning)
    sr.seek(0)
    sw.seek(0)
    n = 0
    for k in range(len(str2)):
        # loop through password start to end and repeat
        if n >= len(pw) - 1:
            n = 0
        p = ord(pw[n])
        n += 1
        # read one character from stream sr
        c = sr.read(1)
        b = ord(c)
        # xor byte with password byte
        t = operator.xor(b, p)
        z = chr(t)
        # advance position to k in stream sw then write one character
        sw.seek(k)
        sw.write(z)
    # reset stream sw to beginning
    sw.seek(0)
    str3 = sw.read()
    if str1.endswith("="):
        return str3
    else:
        return base64.encodestring(str3)

str1 = """\
IwwdG04EHU8PHVgKBw4QGwsMFk8GBg0dHUkXAU4kFxoAHRkGAEkuBgseWD0BCBxlGwccChxJDAcL
SQoOBwUKAA8NWA0cABwIC0dYTywbEQEJSQwHC0kVAAAMAUE="""

password = "nixon"
str2 = xor_crypt(str1, password)
print str2

"""
result -->
Meet me at eighteen hours on Mountain View Road
under the railroad bridge.  Bring the money.
"""

# str1 should not end with a newline character 
# (you will lose your base64 '=' end marker)
str1 = """Meet me at eighteen hours on Mountain View Road
under the railroad bridge.  Bring the money."""

password = "nixon"
str2 = xor_crypt(str1, password)
print str2

"""
result -->
IwwdG04EHU8PHVgKBw4QGwsMFk8GBg0dHUkXAU4kFxoAHRkGAEkuBgseWD0BCBxlGwccChxJDAcL
SQoOBwUKAA8NWA0cABwIC0dYTywbEQEJSQwHC0kVAAAMAUE=
"""