0

duplicates (that I havent found answers in): https://stackoverflow.com/questions/4066361/how-to-obfuscate-python-code How do I protect Python code?

So I have looked at both of the links above ^^ and I have found nothing useful for actually encrypting python scripts and/or obfuscating python code. So I am new to C but experienced in python, and if I wanted to develop commercial python projects my best idea was this:

create a c script and an encrypted&compiled python script The C script would need to simply supply a string encryption key and decrypt it. Just FYI ive never actually tried encryption, and I know this wouldnt be perfect. But I dont need perfect. I just want to make it harder to decompile my python source code, realizing this would be still easy but not AS easy.

I have looked currently at Cython, and I can easily generate a *.c file, now how can I compile this to binary? (with visual studio)

So how could I encrypt my python code and decrypt it from a C script (which I could compile to binary making it significantly harder to edit)?

Community
  • 1
  • 1
pianist1119
  • 319
  • 1
  • 8
  • 19
  • 8
    This desire leads only to suffering. Free yourself of it. – zwol Feb 18 '14 at 20:34
  • 1
    If you intend to decrypt it with a C script anyways won't the user eventually have an unencrypted copy via your C script? – John Dorian Feb 18 '14 at 20:36
  • 1
    Since you only want to inconvenience curious readers, I suggest the simplest possible encryption: flip all zeroes to ones, and ones to zeroes. XORing each byte by 0xFF ought to do it. As an added benefit, the encryption scheme is the same as the decryption scheme, saving 50% effort compared to other schemes. – Kevin Feb 18 '14 at 20:36
  • 4
    Put a web interface on your Python code and sell your software as a service. – Alex Feb 18 '14 at 20:38
  • Store the encrypted Python code as a string in the C program, decrypt it at runtime and run it within an embedded interpreter. But what's the point? Anyone able to understand the Python source should know enough to run the C program using a debugger, breakpoint it correctly and extract the decryption buffer. Alternatively, write your program in C/C++ in the first place and don't use Python :) – isedev Feb 18 '14 at 20:44
  • @isedev I know this, but as I said it would be SIGNIFICANTLY harder which is really all I need – pianist1119 Feb 18 '14 at 21:10
  • @kevin I would decrypt the python script in memory, or use isedev's possible solution – pianist1119 Feb 18 '14 at 21:10

3 Answers3

3

Here's what I would do:

1) Create a C script which produces a key and stores it to a text file

2) Pick up the key and immediately delete the text file upon running Python

3) Use the key to decrypt the really important parts of your Python code (make sure that not having these bits will break your script) then import it all

4) Immediately re-encrypt the important Python bits, and delete the .pyc file

This will be beatable, but you're ok with that.

To encrypt and re-encrypt your python bits, try this code:

from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random

def encrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = Random.new().read(bs - len('Salted__'))
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    out_file.write('Salted__' + salt)
    finished = False
    while not finished:
        chunk = in_file.read(1024 * bs)
        if len(chunk) == 0 or len(chunk) % bs != 0:
            padding_length = (bs - len(chunk) % bs) or bs
            chunk += padding_length * chr(padding_length)
            finished = True
        out_file.write(cipher.encrypt(chunk))

def decrypt(in_file, out_file, password, key_length=32):
    bs = AES.block_size
    salt = in_file.read(bs)[len('Salted__'):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
        if len(next_chunk) == 0:
            padding_length = ord(chunk[-1])
            chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)

So to summarize, here's some pseudo-code:

def main():
    os.system("C_Executable.exe")

    with open("key.txt",'r') as f:
        key = f.read()

    os.remove("key.txt")


    #Calls to decrpyt files which look like this:
    with open("Encrypted file name"), 'rb') as in_file, open("unecrypted file name"), 'wb') as out_file:
        decrypt(in_file, out_file, key)

        os.remove("encrypted file name")

    import fileA, fileB, fileC, etc

    global fileA, fileB, fileC, etc

    #Calls to re-encrypt files and remove unencrypted versions along with .pyc files using a similar scheme to decryption calls

    #Whatever else you want

But just to stress and important point,

Python is not made for this! It is meant to be open and free!

If you find yourself at this juncture with no other alternative, you probably should just use a different language

wnnmaw
  • 5,444
  • 3
  • 38
  • 63
  • "Python is not made for this! It is meant to be open and free!" I realize this but I really cant change languages. And like I said it doesn't have to be perfect – pianist1119 Feb 18 '14 at 22:13
  • Right, that's why I gave you a proper answer as well! – wnnmaw Feb 19 '14 at 03:24
  • Of course this would work for the executed python code, but I still need a C script, and like I said im new to c – pianist1119 Feb 19 '14 at 15:34
  • @pianist1119 I've never used C, so the only help I can provide is to give you [a link](http://stackoverflow.com/questions/11573974/write-to-txt-file), but this should be what you're looking for. – wnnmaw Feb 19 '14 at 15:50
0

The a look at Nuitka project. It's a python compiler that compiles your python scripts to native executable code that uses libpython to run.

http://nuitka.net/

Ilie NEACSU
  • 530
  • 3
  • 12
  • I have yet to try this as I need to get visual studio on my windows dev platfrom, but this looks like just about what I need – pianist1119 Feb 18 '14 at 21:18
  • okay, I just installed visual studio express 2013 from [here](http://www.visualstudio.com/en-us/downloads/) and my nuitka is not detecting it: scons: warning: No version of Visual Studio compiler found... – pianist1119 Feb 18 '14 at 22:43
0

You didn't explain WHY you felt the need to encrypt/decrypt. The answer to which could materially alter any suggestions offered.

For example, let's assume you're trying to protect intellectual property, but like the convenience of coding in python. If this is you motivation, consider cython -- http://cython.org.

But let's say you were more concerned about security (ie: to prevent someone from altering your code without a user's permission). In that case, you could consider some sort of Embedded loader that checksums your python source BEFORE invoking an embedded python interpreter.

I'm sure there are 1/2 dozen other reasons you might want to encrypt.

user590028
  • 11,364
  • 3
  • 40
  • 57
  • Actually -- suggesting cython was my answer. With the caveat it might not accomplish his goal if other than protecting IP. – user590028 Feb 19 '14 at 23:02
  • okay, but how can I build a binary with cython? it gives me a c file with (a bunch) of libraries – pianist1119 Feb 20 '14 at 17:09
  • You'll need to create a setup.py -- see this link http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html – user590028 Feb 20 '14 at 17:11