python通过cython实现加密

摘要:
:paramkey:加密密钥-必须为16、24或32字节长。一些大型文件和机器的大小可能更快。块大小必须可被16整除。
#coding=utf-8
import getopt
import os, sys
import zipfile
from Crypto.Cipher import AES
import random, struct
#加密python3的代码
def transfer3(dir_pref):
    os.system('cython -2 %s.py;'
            'gcc -c -fPIC -I/usr/include/python3.5/ %s.c -o %s.o'
            % (dir_pref, dir_pref, dir_pref))
    os.system('gcc -shared %s.o -o %s.so' % (dir_pref, dir_pref))
    if clear:
        os.system('rm -f %s.c %s.o %s.py' % (dir_pref, dir_pref, dir_pref))
    else:
        os.system('rm -f %s.c %s.o' % (dir_pref, dir_pref))

#加密python2的代码
def transfer2(dir_pref):
    os.system('cython -2 %s.py;'
              'gcc -c -fPIC -I/usr/include/python2.7/ %s.c -o %s.o'
              % (dir_pref, dir_pref, dir_pref))
    os.system('gcc -shared %s.o -o %s.so' % (dir_pref, dir_pref))
    if clear:
        os.system('rm -f %s.c %s.o %s.py' % (dir_pref, dir_pref, dir_pref))
    else:
        os.system('rm -f %s.c %s.o' % (dir_pref, dir_pref))

#加密AI模型
def encrypt_file(in_filename, out_filename=None, chunksize=64*1024):
    """
    使用AES(CBC模式)加密文件给定的密钥。
    :param key: 加密密钥-必须是16、24或32字节长。长按键更安全。
    :param in_filename: 输入的文件的名称
    :param out_filename: 如果为None,将使用“<in_filename>.enc”。
    :param chunksize: 设置函数用于读取和加密文件。大块一些文件和机器的大小可能更快。块大小必须可被16整除。
    :return: None
    """
    if not out_filename:
        out_filename = in_filename + '.enc'
    salt = ''  # 盐值
    key = "{: <32}".format(salt).encode("utf-8")
    #iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
    #encryptor = AES.new(key, AES.MODE_CBC, iv)
    iv = b'0000000000000000'
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    filesize = os.path.getsize(in_filename)

    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            outfile.write(struct.pack('<Q', filesize))
            outfile.write(iv)
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += (' ' * (16 - len(chunk) % 16)).encode("utf-8")

                outfile.write(encryptor.encrypt(chunk))

def zip_dir(dir_path,out_path):
    """
    压缩指定文件夹
    :param dir_path: 目标文件夹路径
    :param out_path: 压缩文件保存路径+xxxx.zip
    :return: 无
    """

    zip = zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED)
    for path, dirnames, filenames in os.walk(dir_path):
        # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
        fpath = path.replace(dir_path, '')
        for filename in filenames:
            zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
    zip.close()

if __name__ == '__main__':
    help_show = '''
python version:
   python3        该代码用于加密python3编写的代码,将.py文件转换成.so文件,达到加密的效果
   python2        该代码用于加密python2编写的代码,将.py文件转换成.so文件,达到加密的效果
   
Options:
  -h,  --help       显示帮助
  -d,  --directory  你需要加密的文件夹
  -o,  --operation  你所需要执行的操作,python3 or python2 or model
  -f,  --file       加密单个py文件
  -c,  --clear      删除原始的py文件
  -m,  --maintain   列出你不需要加密的文件和文件夹,如果是文件夹的话需要加[]
                    例子: -m __init__.py,setup.py,[poc,resource,venv,interface]
  -z,  --zip        加密之后压缩文件

Example:
  python setup.py -f test_file.py -o python2     加密单个文件
  python setup.py -d test_dir -o python2 -m __init__.py,setup.py,[poc/,resource/,venv/,interface/] -c      加密文件夹
  
  python3 setup.py -f test_file.py  -o python3    加密单个文件
  python3 setup.py -d test_dir -o python3 -m __init__.py,setup.py,[poc/,resource/,venv/,interface/] -c      加密文件夹
    '''
    clear = 0
    is_zip = False
    root_name = ''
    operation = ''
    file_name = ''
    m_list = ''
    try:
        options,args = getopt.getopt(sys.argv[1:],"vh:d:f:cm:o:z:",["version","help","directory=","file=","operation=","zip","clear","maintain="])
    except getopt.GetoptError:
        print(help_show)
        sys.exit(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 d.startswith('./'):
                        dir_list.append(d[2:])
                    else:
                        dir_list.append(d)

    if root_name != '':
        if not os.path.exists(root_name):
            print('No such Directory, please check or use the Absolute Path')
            sys.exit(1)
        if os.path.exists('%s_old' % root_name):
            os.system('rm -rf %s_old' % root_name)
        #os.system('cp -r %s %s_old' % (root_name, root_name))   #备份源文件
        try:
            for root, dirs, files in os.walk(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 = file.split('.')[0]
                    dir_pref = root + '/' + pref
                    if file.endswith('.pyc'):
                        os.system('rm -f %s' % dir_pref+'.pyc')
                    elif file.endswith('.so'):
                        pass
                    elif file.endswith('.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)

  

免责声明:文章转载自《python通过cython实现加密》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇asp.net+扫描仪+图片上传RabbitMQ用户角色及权限控制下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

【Python从入门到精通】(十)Python流程控制的关键字该怎么用呢?【收藏下来,常看常新】

您好,我是码农飞哥,感谢您阅读本文,欢迎一键三连哦。这篇文章主要介绍Python中流程控制的关键字的使用,涉及到if else,for,while等关键字 干货满满,建议收藏,需要用到时常看看。 小伙伴们如有问题及需要,欢迎踊跃留言哦~ ~ ~。 前言 有句话说程序就是由流程+数据结构组成。任何程序都是如此。前面花了好几个篇幅来介绍Python中的各种数据...

Centos下zip压缩分包和解压

1>分包 zip要分包,首先要把文件打成zip包后再分割。 zip -qr mypackage.zip /var/www/html/xxxx 其中 -q 表示静默 -r 表示递归子目录。 然后在将mypackage.zip以一个大小分割。 zip -s 10m mypackage.zip --out new_mypackage.zip 将mypack...

Python -扩展C++-Pytorch扩展

1.Python whl 文件和 egg 文件 可以执行和效率是两码事 setup.py用来编译和安装扩展模块。负责编译c++模块,封装成python可以调用的形式 所有能被整合或导入到其它python脚本的代码,都可以被称为扩展 Python调用C库比较简单,不经过任何封装打包成so,直接使用python的ctypes调用即可。 Pytho...

高中信息技术(Python) 必修1 数据与计算 源代码

本文章原文地址:https://www.cnblogs.com/BobHuang/p/15621121.html,原文体验更佳 教材P68中IDLE显示Python版本为3.7.0,所以建议使用Python3.7系列。 第一章 数据与信息 1.1 感知数据 1.2 数据、信息与知识 1.3 数据采集与编码 1.4 数据管理与安全 1.5 数据与大数据 第二...

Linux 利器- Python 脚本编程入门(一)

导读 众所周知,系统管理员需要精通一门脚本语言,而且招聘机构列出的职位需求上也会这么写。大多数人会认为 Bash (或者其他的 shell 语言)用起来很方便,但一些强大的语言(比如 Python)会给你带来一些其它的好处。 首先,我们会使用 Python 的命令行工具,还会接触到 Python 的面向对象特性(这篇文章的后半部分会谈到它)。 学习 P...

Deepin V20编译vim8.2

前言 deepin v20版本,自带的vim8.1版本,不能满足coc.nvim的最低使用要求(不支持浮动窗口),所以自己编译。 编译环境 OS: deepin v20 清理 卸载已存在版本vim sudo apt purge vim vim-gtk vim-runtime vim-gnome vim-common vim-tiny vim-gui-co...