Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to protect Python code

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to protect Python code". In daily operation, I believe many people have doubts about how to protect Python code. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to protect Python code". Next, please follow the editor to study!

Due to the dynamic and open source characteristics of Python, it is difficult for Python code to encrypt well. Some voices in the community believe that such restrictions are true and that commercial protection should be achieved through legal means rather than encrypted source code, while others want to have a means of encryption anyway. As a result, people have come up with a variety of encryption or confusion schemes to achieve the purpose of protecting the source code.

Common source code protection methods are as follows:

Publish .pyc files

Code confusion

Use py2exe

Use Cython

Let's talk about these plans briefly.

1 release .pyc files

1.1 ideas

As we all know, the Python interpreter first generates a .pyc file during the execution of the code, and then interprets and executes the contents of the .pyc file. Of course, the Python interpreter can also execute .pyc files directly. The .pyc file is a binary file, so you can't see the source code directly. Wouldn't it be possible to protect Python code if you release the code to the customer environment with .pyc instead of .py files?

1.2 method

Compiling a .py file to a .pyc file is very easy, but you don't have to run through all the code and pick up the generated .pyc file.

In fact, a library called compileall is provided in the Python standard library, which can be easily compiled.

Execute the following command to compile all .py files in the traversal directory into .pyc files:

Python-m compileall, then delete all .py files in the directory and then package and publish:

$find-name'* .py'- type f-print-exec rm {}

1.3 benefits

Simple and convenient, raised a little bit of source code cracking threshold

With good platform compatibility, .pyc can run wherever py can be run.

1.4 insufficient

Interpreter compatibility is poor, .pyc can only run on specific versions of the interpreter

There is a ready-made decompilation tool with low cost of cracking.

Python-uncompyle6 is such a decompiler with outstanding results.

Execute the following command to decompile the .pyc file into a .py file:

$uncompyle6 * compiled-python-file-pyc-or-pyo*

2 code confusion

If the code is confused to such an extent that even the author has trouble looking at it, can it also achieve the purpose of protecting the source code?

2.1 ideas

Since our goal is confusion, which is to make the code less easy to understand through a series of transformations, we can start like this:-remove comments and documentation. Without these instructions, some of the key logic is not so easy to understand. -change indentation. The perfect indent looks comfortable, and if the indent is long and short, it must be annoying. -add a space in the middle of tokens. This is similar to the effect of changing indentation. -rename functions, classes, variables. Naming directly affects readability, and messy names are a major obstacle to reading comprehension. -insert invalid code on a blank line. This is the trick of using irrelevant codes to disrupt the reading rhythm.

2.2 method

Method 1: use oxyry for confusion

Http://pyob.oxyry.com/ is a website that confuses Python code online, and you can easily confuse it with it.

Suppose we have a piece of Python code that involves classes, functions, parameters, and so on:

# coding: utf-8class A (object): "Description" def _ init__ (self, x, y, default=None): self.z = x + y self.default = default def name (self): return'No Name'def always (): return Truenum = 1a = A (num, 999,100) a.name () always ()

After the confusion of Oxyry, the following code is obtained:

Class A (object): # line:4 "" # line:7 def _ init__ (O0O0O0OO00OO000O0, OO0O0OOOO0000O0OO, OO0OO00O00OO00OOO, OO000OOO0O000OOO0 = None): # line:9 O0O0O0OO00OO000O0 .z = OO0O0OOOO0000O0OO + OO0OO00O00OO00OOO # line:10 O0O0O0OO00OO000O0 .default = OO000OOO0O000OOO0 # line:11 def name (O000O0O0O00O0O0OO): # line:13 return'No Name'#line:14def always (): # line:17 return True # line:18num = 1 # line:21a = A (num, 999,100) # line:22a .name () # line:23always ()

The confused code mainly makes some adjustments on comments, parameter names and spaces, which makes it a little difficult to read.

Method 2: use the pyobfuscate library for confusion

Pyobfuscate is an old Python code confusion library, but it is "getting stronger and stronger".

For the same piece of Python code mentioned above, the effect after pyobfuscate confusion is as follows:

# coding: utf-8if 64-64: i11iIiiIiiif 65-65: O0 / iIii1I11I1II1% OoooooooOO-i1IIiclass o0OO00 (object): if 78-78: i11i. OOooOoO0Oo0O if 10-10: IIiI1I11i11 if 54-54: i11iIi1-oOo0O0Ooo if 2-2: o0 * i1 * ii1IiI1i% OOooOOo / I11i / Ii1I def _ init__ (self, x, y, default = None): self. Z = x + y self. Default = default if 48-48: iII111i% IiII + I1Ii111 / ooOoO0o * Ii1I def name (self): return'No Name' if 46-46: ooOoO0o * I11i-OoooooooOO if 30-30: o0-O0% o0-OoooooooOO * O0 * OoooooooOOdef Oo0o (): return True if 60-60: i1 + I1Ii111-I11i / i1IIi if 40-40: oOooOoO0Oo0O / O0% ooOoO0o + O0 * i1IIiI1Ii11I1Ii1i = 1Ooo = o0OO00 (I1Ii11I1Ii1i, 999,100) Ooo. Name () Oo0o () # dd678faae9ac167bc83abf78e5cb2f3f0688d3a3

Compared with method one, the effect of method two looks better. In addition to renaming classes and functions, adding spaces, and most obviously inserting a number of extraneous pieces of code, it becomes more difficult to read.

2.3 benefits

Simple and convenient, raised a little bit of source code cracking threshold

Good compatibility, as long as the source code logic can be compatible, confused code can also be

2.4 insufficient

You can only confuse a single file, but you can't confuse multiple source files that are related to each other.

The code structure has not changed, and the bytecode can be obtained, so it is not difficult to crack it.

3 using py2exe

3.1 ideas

Py2exe is a tool that converts Python scripts into executables on the Windows platform. The principle is that the source code is compiled into a .pyc file, together with the necessary dependent files, packaged into an executable file.

If the binaries packaged by py2exe are eventually released, won't it achieve the goal of protecting the source code?

3.2 method

The steps for packaging with py2exe are relatively simple.

1) write the entry file. In this example, it is named hello.py:

Print 'Hello World'

2) write setup.py:

From distutils.core import setupimport py2exesetup (console= ['hello.py'])

3) generate executable file

Python setup.py py2exe

The generated executable file is located in dist\ hello.exe.

3.3 benefits

Can be directly packaged into exe for easy distribution and execution

The threshold for cracking is higher than .pyc.

3.4 insufficient

Poor compatibility, can only run on Windows system

The layout in the generated executable file is clear and public, and you can find the .pyc file corresponding to the source code, and then decompile the source code.

4 using Cython

4.1 ideas

Although the main purpose of Cython is to improve performance, based on its principle: compiling .py / .pyx to .c files, and then compiling .c files to .so (Unix) or .pyd (Windows), another benefit is that it is difficult to crack.

4.2 method

The steps for development with Cython are not complicated either.

1) write a file hello.pyx or hello.py:

Def hello (): print ('hello') 2) write setup.py:

2) write setup.py:

From distutils.core import setupfrom Cython.Build import cythonizesetup (name='Hello World app', ext_modules=cythonize ('hello.pyx'))

3) compile to .c, and further compile to .so or .pyd:

Python setup.py build_ext-- inplace executes python-c "from hello import hello;hello ()" to directly reference the hello () function in the generated binaries.

4.3 benefits

The generated binary .so or .pyd files are difficult to crack

At the same time, it brings performance improvement.

4.4 insufficient

Poor compatibility, and may need to be recompiled for different versions of the operating system

Although most Python codes are supported, if some codes are found not to support it, the cost of improvement is high.

At this point, the study on "how to protect Python code" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report