A method to implement encryption of python source code v

Article directory

Due to the confidentiality requirements of the project, the developed projects need to be encrypted. This paper presents two methods.

1. Compile the py file into pyc

Encrypted py code, although compiling to pyc has little effect (it is easy to decompile the source code), but it still has a certain encryption effect. If the project is relatively time-constrained, this method can be used for emergency treatment.

python -m compileall -f -q -b "py folder"

This command will generate the corresponding pyc files from the py files in the directory

Then execute the following command to delete the py file and keep only the pyc file

find . -name "*.py" -type f -print -exec rm -rf {
 } \;

Finally, execute and run the pyc file.

like: python ****.pyc

Note: The encryption of this method must be consistent with the python version used, otherwise an error will be reported. That is to say, the version running  python -m compileall -f -q -b "py文件夹" and  python ****.pyc the version should be consistent.

2. Convert py to so file

2.1 Preparations

pip3 install Cython

sudo apt-get update
sudo apt-get install python-devel 
sudo apt-get install gcc

2.2 Create a new py2so.py file

Fill in the following:

#-* -coding: UTF-8 -* -

"""
Prerequisites for execution:
    System installation python-devel and gcc
    Python install cython
Compile a certain folder:
    python py2so.py BigoModel
Generate result:
    Under the directory build
After the build is complete:
    The startup file also needs py/pyc to play the role. You must copy the startup py/pyc to the compilation directory and delete the so file
"""

import sys, os, shutil, time
from distutils.core import setup
from Cython.Build import cythonize

starttime = time.time()
setupfile= os.path.join(os.path.abspath('.'), __file__)

def getpy(basepath=os.path.abspath('.'), parentpath='', name='', build_dir="build", 
          excepts=(), copyOther=False, delC=False):
    """
    Get the path of the py file
    :param basepath: root path
    :param parentpath: parent path
    :param name: file/folder
    :param excepts: exclude files
    :param copy: whether to copy other files
    :return: iterator of py files
    """
    fullpath = os.path.join(basepath, parentpath, name)
    for fname in os.listdir(fullpath):
        ffile = os.path.join(fullpath, fname)
        if os.path.isdir(ffile) and ffile != os.path.join(basepath, build_dir) and not fname.startswith('.'):
            for f in getpy(basepath, os.path.join(parentpath, name), fname, build_dir, excepts, copyOther, delC):
                yield f
        elif os.path.isfile(ffile):
            # print("\t", basepath, parentpath, name, ffile)
            ext = os.path.splitext(fname)[1]
            if ext == ".c":
                if delC and os.stat(ffile).st_mtime > starttime:
                    os.remove(ffile)
            elif ffile not in excepts and ext not in('.pyc', '.pyx'):
                # print("\t\t", basepath, parentpath, name, ffile)
                if ext in('.py', '.pyx') and not fname.startswith('__'):
                    yield os.path.join(parentpath, name, fname)
                elif copyOther:
                        dstdir = os.path.join(basepath, build_dir, parentpath, name)
                        if not os.path.isdir(dstdir): os.makedirs(dstdir)
                        shutil.copyfile(ffile, os.path.join(dstdir, fname))
        else:
            pass

if __name__ == "__main__":
    currdir = os.path.abspath('.')
    parentpath = sys.argv[1] if len(sys.argv)>1 else "."

    currdir, parentpath = os.path.split(currdir if parentpath == "." else os.path.abspath(parentpath))
    build_dir = os.path.join(parentpath, "build")
    build_tmp_dir = os.path.join(build_dir, "temp")
    print("start:", currdir, parentpath, build_dir)
    os.chdir (currdir)
    try:
        #Get py list
        module_list = list(getpy(basepath=currdir,parentpath=parentpath, build_dir=build_dir, excepts=(setupfile)))
        print(module_list)
        setup(ext_modules = cythonize(module_list),script_args=["build_ext", "-b", build_dir, "-t", build_tmp_dir])
        module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), copyOther=True))
    except Exception as ex:
        print("error! ", ex)
    finally:
        print("cleaning...")
        module_list = list(getpy(basepath=currdir, parentpath=parentpath, build_dir=build_dir, excepts=(setupfile), delC=True))
        if os.path.exists(build_tmp_dir): shutil.rmtree(build_tmp_dir)

    print("complate! time:", time.time()-starttime, 's')

2.3 Compile the project folder

python py2so.py project_dir_path

After the operation is completed,  a  folder project_dir_path will be generated  , all the .os files in the folder will be moved to the corresponding location of the encrypted folder, and the py file in the original folder will be deleted. If it is a startup file, it is recommended to keep it. buildStart the file to run the program.

Compile the py file into pyc:

There is a library available in the Python standard library called  compileall . Simple and convenient, raising a little threshold for source code cracking

The platform compatibility is good, and  py it can run wherever it  pyc can run. But there are ready-made decompilation tools (  python-uncompyle6 ), and the cost of cracking is low. It is recommended to use it when the project time is tight and in an emergency.

Convert py to so file:

The Cython method of encryption is to convert  py files into  so files and  so replace files with  files. The py execution rate will be faster than python, but occasionally some code is not easy to use. It can only be used for testing, and the invalid ones will not be encrypted or take other methods. encryption. The encryption effect is good and it is not easy to be decompiled, but it needs to be tested step by step for the project.

Guess you like

Origin blog.csdn.net/m0_59485658/article/details/125574840