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中的条件判断语句
May 14 Python
python嵌套函数使用外部函数变量的方法(Python2和Python3)
Jan 31 Python
Python多线程爬虫实战_爬取糗事百科段子的实例
Dec 15 Python
Pytorch模型转onnx模型实例
Jan 15 Python
python使用Geany编辑器配置方法
Feb 21 Python
python 实现两个线程交替执行
May 02 Python
解决Keyerror ''acc'' KeyError: ''val_acc''问题
Jun 18 Python
TensorFlow Autodiff自动微分详解
Jul 06 Python
实例讲解Python 迭代器与生成器
Jul 08 Python
python smtplib发送多个email联系人的实现
Oct 09 Python
Python 机器学习工具包SKlearn的安装与使用
May 14 Python
关于python pygame游戏进行声音添加的技巧
Oct 24 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中怎样保持SESSION不过期 原理及方案介绍
2013/08/08 PHP
PHP读书笔记整理_结构语句详解
2016/07/01 PHP
laravel5.4生成验证码的实例讲解
2017/08/05 PHP
ThinkPHP中获取指定日期后工作日的具体日期方法
2018/10/14 PHP
Laravel Eloquent ORM 实现查询表中指定的字段
2019/10/17 PHP
关于javascript DOM事件模型的两件事
2010/07/22 Javascript
JQquery的一些使用心得分享
2012/08/01 Javascript
javascript函数以及基础写法100多条实用整理
2013/01/13 Javascript
JS中怎样判断undefined(比较不错的方法)
2014/03/27 Javascript
javascript里绝对用的上的字符分割函数总结
2014/07/31 Javascript
自己动手手写jQuery插件总结
2015/01/20 Javascript
js实现的牛顿摆效果
2015/03/31 Javascript
使用Raygun来自动追踪AngularJS中的异常
2015/06/23 Javascript
Javascript中匿名函数的调用与写法实例详解(多种)
2016/01/26 Javascript
node通过npm写一个cli命令行工具
2017/10/12 Javascript
微信小程序基于slider组件动态修改标签透明度的方法示例
2017/12/04 Javascript
vue中如何使用ztree
2018/02/06 Javascript
Vue中v-show添加表达式的问题(判断是否显示)
2018/03/26 Javascript
JavaScript反射与依赖注入实例详解
2018/05/29 Javascript
微信小程序购物车、父子组件传值及calc的注意事项总结
2018/11/14 Javascript
layui弹出框Tab选项卡的示例代码
2019/09/04 Javascript
微信小程序用户拒绝授权的处理方法详解
2019/09/20 Javascript
JS面试题中深拷贝的实现讲解
2020/05/07 Javascript
jQuery实现手风琴特效
2021/01/11 jQuery
python实现挑选出来100以内的质数
2015/03/24 Python
简要讲解Python编程中线程的创建与锁的使用
2016/02/28 Python
Python 自动刷博客浏览量实例代码
2017/06/14 Python
Python对List中的元素排序的方法
2018/04/01 Python
Python Learning 列表的更多操作及示例代码
2018/08/22 Python
Python爬虫实现自动登录、签到功能的代码
2020/08/20 Python
利用CSS3实现的文字定时向上滚动
2016/08/29 HTML / CSS
人力资源专业推荐信
2013/11/29 职场文书
工程部岗位职责
2015/02/10 职场文书
python爬虫之selenium库的安装及使用教程
2021/05/23 Python
node.js如何自定义实现一个EventEmitter
2021/07/16 Javascript
Python使用pandas导入csv文件内容的示例代码
2022/12/24 Python