Python with hidden sources

Shahar Gino
2 min readJul 5, 2021

Choose your open-source portion

Python is developed under an OSI-approved open source license, and making it freely usable and distributable, even for commercial use. However, in some occasions, one may wish to keep some (or all) of the sources hidden to public usage, while still allowing to run the code in a normal manner.

A common python library which offers that capability is ccrypt, which is maintained rougeth. The ccrypt library implements few classical encryption algorithms, and it’s available in pip and github.

The strategy would be as following:

  1. Compile your source (*.py → *.pyc)
  2. Pick/generate a secret key and Encrypt your source (*.py → *.py.cpt)
  3. Publish your compiled sources (*.pyc), optionally with their encrypted pairs (*.py.cpt), while keeping the secret key to yourself

Let’s start, by preparing a demo file, termed hello_world.py, as following:

echo "print('hello world')" > hello_world.py

Running this demo file is possible with:

python hello_world.py

which ends up with an “hello world” prompt.

Now, let’s compile, encrypt and rerun:

1. Install ccrypt:

pip install ccrypt

2. Compile the demo-file, using python’s build-in comileall module:

python -m compileall -b hello_world.py

That will generate a new compiled file termed hello_world.pyc.

The compiled file may be launched in a similar way, i.e.:

python hello_world.pyc

which ends up with the same “hello world” prompt.

3. Pick a secret key (e.g. q1w2e3r4) and encrypt the source file:

ccrypt -e -K q1w2e3r4 -f hello_world.py

That will convert the hello_world.py source file into an encrypted file termed hello_world.py.cpt.

Note that the encrypted file can be decrypted back to its source version by applying the following command (with the same key):

ccrypt -d -K q1w2e3r4 -f hello_world.py.cpt

That’s all, simple but yet powerful!

p.s.

Note that there are several libraries out there, for generating keys in an efficient manner. One such example is Sahith02’s key-generator, .e.g.:

pip install key-generatorfrom key_generator.key_generator import generatekey = generate(seed = 101)
print(key.get_key()) # be1679-6ae28652eb-fa7cd6-de96-a8cc

--

--