python项目加密和增加时间许可证

在这里插入图片描述

1.bat,执行如下的命令,第一句是更新或增加许可证
第二句是加密draw_face.py

python offer.py
pyarmor obfuscate -O dist draw_face.py

绘制自制人脸.py,调用加密的代码draw_face代码

import sys
import os
import cv2

# 添加加密模块所在的路径
sys.path.append('C:\\Users\\67099\PycharmProjects\pythonProject1\dist')

try:
    import draw_face  # 导入加密后的模块
except ImportError:
    print("Failed to import draw_face module.")
    sys.exit(1)

# 示例代码调用
image_path = "C:\\Demos\\face_detection1\\imghand\\frame_80.jpg"
input_str = """290 206 119 154 318.0 254.0 1 372.0 255.0 1 341.0 288.0 1 323.0 317.0 1 371.0 317.0 1 0.8"""

resized_image = draw_face.process_image(image_path, input_str)
if resized_image is not None:
    # 显示缩小后的图像
    cv2.imshow("Bounding Box and Key Points", resized_image)
    cv2.waitKey(0)
else:
    cv2.destroyAllWindows()
    print("Failed to process the image.")

offer.py,新增许可证

#!/usr/bin/env python3
from Crypto.Cipher import AES
from binascii import b2a_hex

# 定义加密函数
def encrypt(content):
    # 校验密钥是否为16或16的倍数
    while len(content) % 16:
        content += ' '
    # 把密钥编码为utf-8
    content = content.encode('utf-8')
    # cwillchris123321为加密密钥(必须16位)
    aes = AES.new(b'cwillchris123321', AES.MODE_CBC, b'cwillchris123321')
    # 对密钥进行aes加密
    encrypted_content = aes.encrypt(content)
    # 返回二进制数据的十六进制表示
    return b2a_hex(encrypted_content)

# 生成许可证文件
def gen_license_file(username, expiry_date):
    license_file = './License.dat'
    # 设置用户名和脚本使用的有效期
    with open(license_file, 'w') as LF:
        # 写入用户名
        LF.write(f'Username : {username}\n')
        # 写入有效期
        LF.write(f'Date : {expiry_date}\n')
        # 生成签名,防止篡改
        sign = encrypt(f'{username}#{expiry_date}')
        # 将生成的签名进行utf-8编码后写入许可证文件
        LF.write(f'Sign : {sign.decode("utf-8")}\n')

if __name__ == '__main__':
    # 示例调用,生成许可证文件
    gen_license_file('example_user', '20240624')

在这里插入图片描述
draw_face.py,要加密的程序,注意要加密的程序上面增加下面这段话

from Crypto.Cipher import AES
from binascii import a2b_hex
import datetime

def decrypt(encrypted_content):
    encrypted_content = a2b_hex(encrypted_content)
    aes = AES.new(b'cwillchris123321', AES.MODE_CBC, b'cwillchris123321')
    decrypted_content = aes.decrypt(encrypted_content)
    return decrypted_content.decode('utf-8').strip()

def verify_license_file():
    license_file = './License.dat'
    try:
        with open(license_file, 'r') as LF:
            lines = LF.readlines()
            username = lines[0].split(' : ')[1].strip()
            date = lines[1].split(' : ')[1].strip()
            sign = lines[2].split(' : ')[1].strip()

            expected_sign = decrypt(sign)
            if expected_sign == f'{username}#{date}':
                current_date = datetime.datetime.now().strftime('%Y%m%d')
                if current_date <= date:
                    return True
                else:
                    print('License has expired.')
            else:
                print('License is invalid.')
    except Exception as e:
        print(f'Error verifying license: {e}')
    return False

if not verify_license_file():
    raise SystemExit('Invalid or expired license. Please contact support.')

完整的代码如下所示

from Crypto.Cipher import AES
from binascii import a2b_hex
import datetime

def decrypt(encrypted_content):
    encrypted_content = a2b_hex(encrypted_content)
    aes = AES.new(b'cwillchris123321', AES.MODE_CBC, b'cwillchris123321')
    decrypted_content = aes.decrypt(encrypted_content)
    return decrypted_content.decode('utf-8').strip()

def verify_license_file():
    license_file = './License.dat'
    try:
        with open(license_file, 'r') as LF:
            lines = LF.readlines()
            username = lines[0].split(' : ')[1].strip()
            date = lines[1].split(' : ')[1].strip()
            sign = lines[2].split(' : ')[1].strip()

            expected_sign = decrypt(sign)
            if expected_sign == f'{username}#{date}':
                current_date = datetime.datetime.now().strftime('%Y%m%d')
                if current_date <= date:
                    return True
                else:
                    print('License has expired.')
            else:
                print('License is invalid.')
    except Exception as e:
        print(f'Error verifying license: {e}')
    return False

if not verify_license_file():
    raise SystemExit('Invalid or expired license. Please contact support.')


import cv2
import numpy as np

def process_image(image_path, input_str):
    # 读取图像
    image = cv2.imread(image_path)

    # 检查图像是否成功加载
    if image is None:
        print(f"Error: Unable to load image from {image_path}")
        return None

    # 将输入字符串按行分割
    lines = input_str.strip().split('\n')

    # 遍历每行
    for line in lines:
        # 将每行按空格分割,获取所有数字
        values = line.split()

        # 提取前4个数字,代表框的范围
        box = [int(values[i]) for i in range(4)]

        # 将浮点数列表分组成(x, y)坐标对,每组保留第1、2个数字,去掉第3个数字,直到第19个数字
        keypoints = [(float(values[i]), float(values[i + 1]), float(values[i + 2])) for i in range(4, 19, 3)]

        # 将坐标转换为整数
        keypoints = np.array(keypoints, dtype=np.int32)

        # 遍历关键点,使用不同颜色进行标记
        for point in keypoints:
            if point[2] == 1.0:
                cv2.circle(image, (point[0], point[1]), 5, (0, 0, 255), -1)  # 红色
            else:
                cv2.circle(image, (point[0], point[1]), 5, (0, 255, 0), -1)  # 绿色

        # 在图像上绘制边界框
        cv2.rectangle(image, (box[0], box[1]), (box[0] + box[2], box[1] + box[3]), (0, 0, 255), 2)

    # 等比例缩小图像
    scale_factor = 0.5  # 缩小50%
    width = int(image.shape[1] * scale_factor)
    height = int(image.shape[0] * scale_factor)
    dim = (width, height)

    resized_image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)

    return resized_image

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值