python通过cython加密代码


Posted in Python onDecember 11, 2020
#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加密代码的详细内容,更多关于python cpython加密的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python获取文件扩展名的方法
Jul 06 Python
Python读写txt文本文件的操作方法全解析
Jun 26 Python
浅谈Python生成器generator之next和send的运行流程(详解)
May 08 Python
Python实现的爬取网易动态评论操作示例
Jun 06 Python
django组合搜索实现过程详解(附代码)
Aug 06 Python
Win10+GPU版Pytorch1.1安装的安装步骤
Sep 27 Python
Python的几种主动结束程序方式
Nov 22 Python
python实现logistic分类算法代码
Feb 28 Python
Keras SGD 随机梯度下降优化器参数设置方式
Jun 19 Python
Python Opencv图像处理基本操作代码详解
Aug 31 Python
Python使用paramiko连接远程服务器执行Shell命令的实现
Mar 04 Python
Python 把两层列表展开平铺成一层(5种实现方式)
Apr 07 Python
python 对象真假值的实例(哪些视为False)
Dec 11 #Python
Python排序函数的使用方法详解
Dec 11 #Python
Python数据分析库pandas高级接口dt的使用详解
Dec 11 #Python
python 自定义异常和主动抛出异常(raise)的操作
Dec 11 #Python
解决python 在for循环并且pop数组的时候会跳过某些元素的问题
Dec 11 #Python
基于Python中Remove函数的用法讨论
Dec 11 #Python
在 Python 中使用 7zip 备份文件的操作
Dec 11 #Python
You might like
php 动态多文件上传
2009/01/18 PHP
PHP弹出对话框技巧详细解读
2015/09/26 PHP
实现WordPress主题侧边栏切换功能的PHP脚本详解
2015/12/14 PHP
PHP连接MySQL数据库操作代码实例解析
2020/07/11 PHP
laravel数据库查询结果自动转数组修改实例
2021/02/27 PHP
Jquery.LazyLoad.js修正版下载,实现图片延迟加载插件
2011/03/12 Javascript
查找Oracle高消耗语句的方法
2014/03/22 Javascript
js点击返回跳转到指定页面实现过程
2020/08/20 Javascript
JQuery插件Marquee.js实现无缝滚动效果
2016/04/26 Javascript
JS未跨域操作iframe里的DOM
2016/06/01 Javascript
基于JS+Canves实现点击按钮水波纹效果
2016/09/15 Javascript
angular ngClick阻止冒泡使用默认行为的方法
2016/11/03 Javascript
NodeJS实现图片上传代码(Express)
2017/06/30 NodeJs
vue中页面跳转拦截器的实现方法
2017/08/23 Javascript
Nodejs调用WebService的示例代码
2017/09/29 NodeJs
利用vue+elementUI实现部分引入组件的方法详解
2017/11/22 Javascript
在vue组件中使用axios的方法
2018/03/16 Javascript
JS中创建自定义类型的常用模式总结【工厂模式,构造函数模式,原型模式,动态原型模式等】
2019/01/19 Javascript
layer实现登录弹框,登录成功后关闭弹框并调用父窗口的例子
2019/09/11 Javascript
微信小程序实现滑动翻页效果(完整代码)
2019/12/06 Javascript
VsCode里的Vue模板的实现
2020/08/12 Javascript
python Django连接MySQL数据库做增删改查
2013/11/07 Python
Python实现豆瓣图片下载的方法
2015/05/25 Python
Python中Django框架下的staticfiles使用简介
2015/05/30 Python
Python在图片中添加文字的两种方法
2017/04/29 Python
Python使用matplotlib绘制三维图形示例
2018/08/25 Python
Python3解释器知识点总结
2019/02/19 Python
使用 Python 遍历目录树的方法
2020/02/29 Python
python中round函数保留两位小数的方法
2020/12/04 Python
html5记忆翻牌游戏实现思路及代码
2013/07/25 HTML / CSS
PHP面试题集
2016/12/18 面试题
股东合作协议书
2014/04/14 职场文书
2014年财务工作自我评价
2014/09/23 职场文书
判缓刑人员个人思想汇报
2014/10/10 职场文书
什么是执行力?9个故事告诉您:成功绝非偶然!
2019/07/05 职场文书
java协程框架quasar和kotlin中的协程对比分析
2022/02/24 Java/Android