SoFunction
Updated on 2024-12-16

python encryption code via cython

python通过cython加密代码

 更新时间:2020年12月11日 17:00:32   作者:一个不懂代码的程序猿  
This article mainly introduces the python encryption through cython sample code to help you encrypt their python code to improve security, interested parties can refer to the following
#coding=utf-8
import getopt
import os, sys
import zipfile
from  import AES
import random, struct
#Encrypted python3 code
def transfer3(dir_pref):
    ('cython -2 %;'
            'gcc -c -fPIC -I/usr/include/python3.5/ % -o %'
            % (dir_pref, dir_pref, dir_pref))
    ('gcc -shared % -o %' % (dir_pref, dir_pref))
    if clear:
        ('rm -f % % %' % (dir_pref, dir_pref, dir_pref))
    else:
        ('rm -f % %' % (dir_pref, dir_pref))
 
#Encrypted python2 code
def transfer2(dir_pref):
    ('cython -2 %;'
              'gcc -c -fPIC -I/usr/include/python2.7/ % -o %'
              % (dir_pref, dir_pref, dir_pref))
    ('gcc -shared % -o %' % (dir_pref, dir_pref))
    if clear:
        ('rm -f % % %' % (dir_pref, dir_pref, dir_pref))
    else:
        ('rm -f % %' % (dir_pref, dir_pref))
 
#Encrypted AI models
def encrypt_file(in_filename, out_filename=None, chunksize=64*1024):
    """
    Encrypts the file with the given key using AES (CBC mode).
    :param key: Encryption key - must be 16, 24 or 32 bytes long. Longer keys are more secure.
    :param in_filename: Name of the input file
    :param out_filename: If None, "<in_filename>.enc" will be used.
    :param chunksize: set function to read and encrypt files. Large chunks of some file and machine sizes may be faster. The chunk size must be divisible by 16.
    :return: None
    """
    if not out_filename:
        out_filename = in_filename + '.enc'
    salt = ''  # Salt value
    key = "{: <32}".format(salt).encode("utf-8")
    #iv = ''.join(chr((0, 0xFF)) for i in range(16))
    #encryptor = (key, AES.MODE_CBC, iv)
    iv = b'0000000000000000'
    encryptor = (key, AES.MODE_CBC, iv)
    filesize = (in_filename)
 
    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            (('<Q', filesize))
            (iv)
            while True:
                chunk = (chunksize)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += (' ' * (16 - len(chunk) % 16)).encode("utf-8")
 
                ((chunk))
 
def zip_dir(dir_path,out_path):
    """
    Compress the specified folder
    :param dir_path: Destination folder path
    :param out_path: path where the compressed file is saved+
    :return: none
    """
 
    zip = (out_path, "w", zipfile.ZIP_DEFLATED)
    for path, dirnames, filenames in (dir_path):
        # Remove the destination and path, only the files and folders under the destination folder will be compressed.
        fpath = (dir_path, '')
        for filename in filenames:
            ((path, filename), (fpath, filename))
    ()
 
if __name__ == '__main__':
    help_show = '''
python version.
   python3 This code is used to encrypt code written in python3, converting .py files into .so files to achieve the effect of encryption.
   python2 This code is used to encrypt code written in python2, converting .py files to .so files to achieve the effect of encryption.

Options.
  -h, --help show help
  -d, --directory The folder you want to encrypt.
  -o, --operation The operation you need to perform, python3 or python2 or model.
  -f, --file Encrypts a single py file.
  -c, --clear Delete the original py file.
  -m, --maintain Lists files and folders you don't need to encrypt, add [] if they are folders.
                    Example: -m __init__.py,,[poc,resource,venv,interface]
  -z, --zip Compress files after encryption.

Example.
  python -f test_file.py -o python2 Encrypt a single file.
  python -d test_dir -o python2 -m __init__.py,,[poc/,resource/,venv/,interface/] -c encrypt folder

  python3 -f test_file.py -o python3 Encrypting a single file
  python3 -d test_dir -o python3 -m __init__.py,,[poc/,resource/,venv/,interface/] -c Encrypted folder
    '''
    clear = 0
    is_zip = False
    root_name = ''
    operation = ''
    file_name = ''
    m_list = ''
    try:
        options,args = ([1:],"vh:d:f:cm:o:z:",["version","help","directory=","file=","operation=","zip","clear","maintain="])
    except :
        print(help_show)
        (1)
 
    for key, value in options:
        if key in ['-h', '--help']:
            print(help_show)
        elif key in ['-c', '--clear']:
            clear = 1
        elif key in ['-d', '--directory']:
            root_name = value
        elif key in ['-f', '--file']:
            file_name = value
        elif key in ['-o', '--operation']:
            operation = value
        elif key in ['-z','--zip']:
            is_zip = True
        elif key in ['-m', '--maintain']:
            m_list = value
            file_flag = 0
            dir_flag = 0
            if m_list.find(',[') != -1:
                tmp = m_list.split(',[')
                file_list = tmp[0]
                dir_list = tmp[1:-1]
                file_flag = 1
                dir_flag = 1
            elif m_list.find('[') != -1:
                dir_list = m_list[1:-1]
                dir_flag = 1
            else:
                file_list = m_list.split(',')
                file_flag = 1
            if dir_flag == 1:
                dir_tmp = dir_list.split(',')
                dir_list=[]
                for d in dir_tmp:
                    if ('./'):
                        dir_list.append(d[2:])
                    else:
                        dir_list.append(d)
 
    if root_name != '':
        if not (root_name):
            print('No such Directory, please check or use the Absolute Path')
            (1)
        if ('%s_old' % root_name):
            ('rm -rf %s_old' % root_name)
        #('cp -r %s %s_old' % (root_name, root_name)) #Backup source files
        try:
            for root, dirs, files in (root_name):
                for file in files:
                    if m_list != '':
                        skip_flag = 0
                        if dir_flag == 1:
                            for dir in dir_list:
                                if (root+'/').startswith(root_name + '/' + dir):
                                    skip_flag = 1
                                    break
                            if skip_flag:
                                continue
                        if file_flag == 1:
                            if file in file_list:
                                continue
                    pref = ('.')[0]
                    dir_pref = root + '/' + pref
                    if ('.pyc'):
                        ('rm -f %s' % dir_pref+'.pyc')
                    elif ('.so'):
                        pass
                    elif ('.py'):
                        if operation == 'python3':
                            transfer3(dir_pref)
                        elif operation == 'python2':
                            transfer2(dir_pref)
                        else:
                            pass
        except Exception as e:
            print(e)
    if file_name != '':
        try:
            dir_pref = file_name.split('.')[0]
            if operation == 'python3':
                transfer3(dir_pref)
            elif operation == 'python2':
                transfer2(dir_pref)
            else:
                pass
        except Exception as e:
            print(e)
    if is_zip:
        zip_dir(root_name,root_name+'.zip')
    if operation == 'model':
        encrypt_file(root_name)

Above is the details of python encryption code via cython, for more information about python cpython encryption please follow my other related articles!

  • python
  • cpython
  • encrypted

Related articles

  • How to use property in python3

    This article is mainly for you to introduce in detail the use of property in python3, with certain reference value, interested partners can refer to it
    2019-04-04
  • Python speech synthesis of third-party libraries gTTs/pyttsx3/speech cross-review (with how to use)

    Python is a very powerful scripting language can be used to achieve a variety of complex applications, one of which is the text-to-speech, that is, the text is converted into sound to send out, the following article introduces the third-party library on Python speech synthesis gTTs/pyttsx3/speech cross-reviewed information, the text also introduces a detailed method of use, the Friends who need it can refer to the following
    2023-05-05
  • Python : turtle color control example details

    Today, I'd like to share a Python : turtle color control examples in detail, with good reference value, I hope it will help you. Together follow the editor over to see it
    2020-01-01
  • Intelligent Parking Lot License Plate Recognition Billing System Based on Python

    This article introduces how to use Python to achieve a smart parking lot license plate recognition billing system, the sample code in the text explains the details, interested partners can try their hands!
    2022-04-04
  • python implementation of the storage of data to txt and pdf documents and garbled problem resolution

    This article introduces the python implementation of the storage of data to txt and pdf documents and garbled problem solving, with good reference value, I hope to help you. Follow the editor over to see it together
    2021-03-03
  • Python Pandas common function method summary

    Today to bring you knowledge of Python, the article centers around the Pandas common function method to start, the text has a very detailed introduction and code examples, need friends can refer to the next!
    2021-06-06
  • A simple understanding of Django ORM common field types and parameter configuration

    This article introduces a simple understanding of Django ORM commonly used field types and parameter configurations, the text through the sample code is very detailed, for everyone's learning or work has a certain reference learning value, you can refer to the following friends
    2020-01-01
  • Priority queue (priority queue) and heap (heap) in Python

    This article introduces the priority queue (priority queue) and heap (heap) in Python, with good reference value, I hope to help you. If there is any error or not fully considered, please do not hesitate to give advice!
    2022-09-09
  • Python Object-Oriented Programming Basics Explained (I)

    This article introduces the Python object-oriented programming foundation analysis of the relevant content, if you want to understand the basic part of Python programming, this article is worth a look, the need for friends can refer to the following.
    2017-10-10
  • Example of building an exponential smoothing prediction model in python

    Today I'm going to share a python build exponential smoothing prediction model example, with good reference value, I hope to help you. Together follow the editor over to see it
    2019-11-11

Latest Comments