python通过cython加密代码

#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加密的资料请关注我们其它相关文章!

(0)

相关推荐

  • Python的加密模块md5、sha、crypt使用实例

    MD5(Message-Digest Algorithm 5) 模块用于计算信息密文(信息摘要),得出一个128位的密文.sha模块跟md5相似,但生成的是160位的签名.使用方法是相同的. 如下实例是使用md5的: 复制代码 代码如下: # /usr/bin/python # -*- coding:utf-8 -*- import base64 try:     import hashlib     hash = hashlib.md5() except ImportError:     #

  • 如何使用Cython对python代码进行加密

    Cython是属于PYTHON的超集,他首先会将PYTHON代码转化成C语言代码,然后通过c编译器生成可执行文件.优势:资源丰富,适合快速开发.翻译成C后速度比较快,在windows环境中用cython加密后的文件后缀是pyd文件,在linux环境中加密后的问题后缀是so文件,下面以linux环境作为演示 环境准备 系统环境:centos 7 Python版本:python3.x 需要的第三方包:cython 加密代码部分 encryption.py from distutils.core im

  • Python实现ElGamal加密算法的示例代码

    在密码学中,ElGamal加密算法是一个基于迪菲-赫尔曼密钥交换的非对称加密算法.它在1985年由塔希尔·盖莫尔提出.GnuPG和PGP等很多密码学系统中都应用到了ElGamal算法. ElGamal加密算法可以定义在任何循环群G上.它的安全性取决于G上的离散对数难题. 使用Python实现ElGamal加密算法,完成加密解密过程,明文使用的是125位数字(1000比特). 代码如下: import random from math import pow a = random.randint(2

  • 详解python实现可视化的MD5、sha256哈希加密小工具

    本文主要介绍了详解python实现可视化的MD5.sha256哈希加密小工具,分享给大家,具体如下: 效果图: 刚启动的状态 输入文本.触发加密按钮后支持复制 超过十条不全量显示 代码 import hashlib import tkinter as tk #窗口控制 windowss=tk.Tk() windowss.title('Python_md5')#窗口title,并非第一行 windowss.geometry('820x550') windowss.resizable(width=T

  • python使用rsa加密算法模块模拟新浪微博登录

    PC登录新浪微博时,在客户端用js预先对用户名.密码都进行了加密,而且在POST之前会GET一组参数,这也将作为POST_DATA的一部分.这样,就不能用通常的那种简单方法来模拟POST登录(比如人人网). 通过爬虫获取新浪微博数据,模拟登录是必不可少的. 1.在提交POST请求之前,需要GET获取四个参数(servertime,nonce,pubkey和rsakv),不是之前提到的只是获取简单的servertime,nonce,这里主要是由于js对用户名.密码加密方式改变了. 1.1 由于加密

  • Python使用MD5加密字符串示例

    Python加密模块有好几个,但无论是哪种加密方式都需要先导入相应的加密模块然后再使用模块对字符串加密. 先导入md5加密所需模块: 复制代码 代码如下: import hashlib 创建md5对象 复制代码 代码如下: m = hashlib.md5() 生成加密串,其中 password 是要加密的字符串 复制代码 代码如下: m.update('password') 获取加密串 复制代码 代码如下: psw = m.hexdigest() 输出 复制代码 代码如下: print psw

  • python RSA加密的示例

    RSA加密是一种非对称加密,通常使用公钥加密,私钥解密,私钥签名,公钥验签. 在公开密钥密码体制中,加密密钥(即公开密钥)PK是公开信息,而解密密钥(即秘密密钥)SK是需要保密的.RSA算法通常是先生成一对RSA密钥,其中之一是保密密钥,由用户保存:另一个为公开密钥,可对外公开,甚至可在网络服务器中注册. RSA是一种公钥密码算法,加密算法是将明文m(m<n是一个整数)加密成密文c,即明文数字m的 E 次方求mod N,也就是将明文与自己相乘E次,然后结果除以N求余数,余数就是密文c,E和N组合

  • Python实现AES加密,解密的两种方法

    第一种 import base64 from Crypto.Cipher import AES # 密钥(key), 密斯偏移量(iv) CBC模式加密 def AES_Encrypt(key, data): vi = '0102030405060708' pad = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16) data = pad(data) # 字符串补位 cipher = AES.new(key.encode('utf8

  • Python实现加密的RAR文件解压的方法(密码已知)

    博主之前在网上找了很多资料,发现rarfile库不能直接调用,需要安装unrar模块,下面将详细介绍整个实现流程. 第一步:安装unrar模块,直接pip install unrar可能会找不到库,需要下载unrar library,也就是UnRAR.dll,下载地址为:http://www.rarlab.com/rar/UnRARDLL.exe: 第二步:将unrar安装路径添加到系统环境变量,64位操作系统的路径为C:\Program Files (x86)\UnrarDLL\x64,然后还

  • Python使用Pycrypto库进行RSA加密的方法详解

    密码与通信 密码技术是一门历史悠久的技术.信息传播离不开加密与解密.密码技术的用途主要源于两个方面,加密/解密和签名/验签 在信息传播中,通常有发送者,接受者和窃听者三个角色.假设发送者Master想要写信给接受者Ghost,可是又不想信的内容被别人看到,因此Master需要先对信加密,而Ghost收到信之后又能解密.这样别的人即使窃听盗取了密文也无法解密.其次,如果窃听者并不像破译内容,而是伪造Master发消息给Ghost,那么Master发消息前就得先对机密内容进行签名. 密码技术 为了进

随机推荐