How can I get python XOR to Decrypt a Multi-line String?

1.9k Views Asked by At

I've been working on a project for a while, here's what's going on with my code

For example, if my code is:

code = """
def mymath(number):
    return number + 2

print mymath(5)
"""
print code
exec(code)

Works Fine, however, when I encrypt that information python only prints out / executes one line of code?

code = """NikTUSIgBxwMFB5aSSkaLDApB1h1THk=
cmxVUSE0HhYKB1ISQXViSw==
X0Y=
Ij4cHzthHhUbHRFYDSRHcntBfw==
"""
print decrypt(code)
exec(decrypt(code))

This Simply prints:

==== RESTART:
def mathcalc(number):


>>> 

Finally, here's my Broken complete code if you need to look at it:

from Crypto.Cipher import XOR
import base64

def encrypt(plaintext):
    cipher = XOR.new('RLuqOAstour9aGoA')
    return base64.b64encode(cipher.encrypt(plaintext))

def decrypt(ciphertext):
    cipher = XOR.new('RLuqOAstour9aGoA')
    return cipher.decrypt(base64.b64decode(ciphertext))


#Code stores the encrypted information
code = """NikTUSIgBxwMFB5aSSkaLDApB1h1THk=
cmxVUSE0HhYKB1ISQXViSw==
X0Y=
Ij4cHzthHhUbHRFYDSRHcntBfw==
"""
print decrypt(code)
exec(code)

How might I get python to do this with all the lines of code? I'd like it to hopefully be able to be executed using the exec() function as well.

1

There are 1 best solutions below

3
On BEST ANSWER

It seems that when creating code, you base64-encoded your piece of Python code line by line. Don't do that. base64 encoding is not meant to work piece by piece, it's meant to encode a complete block of data as one single unit, so when the decoder sees the = symbol which appears at the end of each line, it thinks it's reached the end and there is nothing left.

The proper way to solve this is to go back to your original code and pass the entire string to a base64 encoder, not just one line at a time. Use that for code. You should only get equals signs at the end.

However, if you found yourself in this situation and you didn't have the original data, you could apply the base64 decoding and decryption line by line, something like this:

[XOR.new(key).decrypt(base64.b64decode(e)) for e in code.splitlines()]

where key is the encryption key.