Python scripts can be protected in order to avoid stealing of intellectual property, algorithms or anything else you want to hide from the final user. As using an interpreter (usually CPython), your code is translated from human readable language (python) in python bytecodes (stored in __pycache__
) ; with some modifications of CPython source code, you could extract all the code (even if it’s obfuscated) without difficulties.
<aside> ℹ️ How to dump code object to disk ?
Compile Python from source. Modify the _PyEval_EvalFrameDefault
function such that it dumps the code object to disk.
</aside>
In this article, I propose two ways of protecting your python scripts. An easy one using a python tool named PyArmor which relies on an external unknown not open-source library and a solider one using a tool which I appreciate whose name is Enigma Protector (it protects executable on windows 💠).
Protection level : ⭐⭐
Protection level on Windows : ⭐⭐⭐
Difficulty to implement : ⭐
✅ Pros | ❌ Cons |
---|---|
Multiple platforms | Using external C compiled https://github.com/dashingsoft/pyarmor-core (not open-source) |
Full https://github.com/dashingsoft/pyarmor | |
implementation (open-source) | Virtual Machine only for Windows |
52 $ by project | Runtime obfuscation of python script only |
Hardware lock | Weaker protection than Enigma Protector |
Seamless Replacement | No trial (need a double distribution) |
Easy packing with PyInstaller | Need to have a licence file for each final user |
Can protect the complete program | PyArmor Core need an update for each new plateform/python version |
After buying a capsule on the website, register the program.
pyarmor register pyarmor-regfile-1.zip
pyarmor register
> INFO PyArmor Version 7.4.1
> INFO Python 3.10.4
> PyArmor Version 7.4.1
> Registration Code: pyarmor-vax-000****
> This code is authorized to "Rémi MEVAERE (Personal) <****@*****.fr>"
The program we want to protect is composed of two scripts :
File : main.py
from fibonacci import fibonacci
print("Welcome to the test program")
nbr = input("Please enter an integer : ")
if None != (fib_list := fibonacci(nbr)):
print("Sequence of Fibonacci : ")
print(fib_list)
input("Press key to stop")
File : fibonacci.py
def fibonacci(n):
try:
nbr = int(n)
if nbr <= 0:
raise ValueError
FibArray = [0, 1]
for i in range(nbr - 2):
FibArray.append(FibArray[-1] + FibArray[-2])
return FibArray
except:
print("Incorrect input")
return None
First we want to protect the script fibonacci.py
. It’s recommended to use --advanced
parameter to improve the protection but it doesn’t change anything for this demonstration. To protect seriously your script/program you need to use this parameter, see the manual.