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中用max()方法求最大值的介绍
May 15 Python
使用Python+Splinter自动刷新抢12306火车票
Jan 03 Python
Numpy数据类型转换astype,dtype的方法
Jun 09 Python
Python决策树之基于信息增益的特征选择示例
Jun 25 Python
深入理解Python异常处理的哲学
Feb 01 Python
Django文件上传与下载(FileFlid)
Oct 06 Python
Python 模拟动态产生字母验证码图片功能
Dec 24 Python
Django静态资源部署404问题解决方案
May 11 Python
Python Socket TCP双端聊天功能实现过程详解
Jun 15 Python
PyTorch: Softmax多分类实战操作
Jul 07 Python
详解python tkinter 图片插入问题
Sep 03 Python
解决pytorch下出现multi-target not supported at的一种可能原因
Feb 06 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下通过file_get_contents的代理使用方法
2011/02/16 PHP
phpexcel导出excel的颜色和网页中的颜色显示不一致
2012/12/11 PHP
Laravel 5框架学习之数据库迁移(Migrations)
2015/04/08 PHP
关于php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的问题
2015/12/21 PHP
PHP里面把16进制的图片数据显示在html的img标签上(实现方法)
2017/05/02 PHP
php伪静态验证码不显示的解决方案
2019/09/26 PHP
JQuery与iframe交互实现代码
2009/12/24 Javascript
jQuery源码分析-04 选择器-Sizzle-工作原理分析
2011/11/14 Javascript
关于scrollLeft,scrollTop的浏览器兼容性测试
2013/03/19 Javascript
JavaScript实现复制功能各浏览器支持情况实测
2013/07/18 Javascript
Javascript中封装window.open解决不兼容问题
2014/09/28 Javascript
详谈JavaScript内存泄漏
2014/11/14 Javascript
jQuery中slideUp 和 slideDown 的点击事件
2015/02/26 Javascript
实例代码详解jquery.slides.js
2015/11/16 Javascript
jquery输入数字随机抽奖特效的简单实现代码
2016/06/10 Javascript
js实现悬浮窗效果(支持拖动)
2017/03/09 Javascript
前端开发不得不知的10个最佳ES6特性
2017/08/30 Javascript
使用element-ui +Vue 解决 table 里包含表单验证的问题
2020/07/17 Javascript
nestjs中异常过滤器Exceptionfilter的具体使用
2021/02/07 Javascript
python实现得到一个给定类的虚函数
2014/09/28 Python
python实现在控制台输入密码不显示的方法
2015/07/02 Python
Django权限机制实现代码详解
2018/02/05 Python
django 单表操作实例详解
2019/07/30 Python
Python实现初始化不同的变量类型为空值
2020/06/02 Python
Python自动化测试中yaml文件读取操作
2020/08/20 Python
详解Python中如何将数据存储为json格式的文件
2020/11/18 Python
eBay奥地利站:eBay.at
2019/07/24 全球购物
Nip + Fab官网:英国美容品牌
2019/08/26 全球购物
Derek Rose官网:英国高档睡衣、家居服和内衣品牌
2020/01/18 全球购物
介绍一下EJB的体系结构
2012/08/01 面试题
体育活动总结范文
2014/05/04 职场文书
市级优秀班主任事迹材料
2014/05/13 职场文书
企业活动策划方案
2014/06/02 职场文书
大学生工作求职信
2014/06/23 职场文书
村主任群众路线教育实践活动个人对照检查材料思想汇报
2014/10/01 职场文书
了解Kubernetes中的Service和Endpoint
2022/04/01 Servers