当前位置: 代码网 > it编程>前端脚本>Python > 使用Python实现一个安全封装EXE文件加密保护工具

使用Python实现一个安全封装EXE文件加密保护工具

2025年12月18日 Python 我要评论
一、概述这个python脚本实现了一个强大的exe文件加密保护工具,它能够将任何windows可执行文件封装到一个带密码保护的gui程序中。核心功能包括:使用aes-256加密算法保护原始exe文件创

一、概述

这个python脚本实现了一个强大的exe文件加密保护工具,它能够将任何windows可执行文件封装到一个带密码保护的gui程序中。核心功能包括:

  • 使用aes-256加密算法保护原始exe文件
  • 创建美观的密码验证界面
  • 支持自定义程序图标
  • 自动处理pyinstaller打包过程
  • 修复tkinter在打包环境中的运行时问题

二、核心功能模块

1. 文件加密模块

def encrypt_file(key, in_path, out_path):
    """使用aes-256 cbc模式加密文件"""
    iv = get_random_bytes(16)  # 生成随机初始化向量
    cipher = aes.new(key, aes.mode_cbc, iv)  # 创建加密器
    
    with open(in_path, 'rb') as f_in:
        data = f_in.read()  # 读取原始文件内容
    
    # 加密并填充数据
    ct_bytes = cipher.encrypt(pad(data, aes.block_size))
    encrypted = iv + ct_bytes  # 组合iv和密文
    
    with open(out_path, 'wb') as f_out:
        f_out.write(encrypted)  # 写入加密文件

2. stub程序生成器

这是加密后的exe文件运行时显示的解锁界面核心代码:

def generate_stub_code(password_hash, encrypted_data_base64):
    """生成包含密码验证界面的python代码"""
    return f'''#!/usr/bin/env python
# tkinter运行时修复 - 解决打包环境下的关键问题
def fix_tkinter_runtime():
    if getattr(sys, 'frozen', false):
        base_path = sys._meipass
        tk_data_dir = os.path.join(base_path, '_tk_data')
        if not os.path.exists(tk_data_dir):
            tk_data_dir = os.path.join(base_path, 'tk', 'data')
        os.environ['tkdata'] = tk_data_dir  # 设置环境变量

# 在创建tkinter界面之前调用修复函数
fix_tkinter_runtime()

# 密码验证逻辑
def check_password():
    password = password_entry.get()
    key = hashlib.sha256(password.encode()).digest()  # 从密码生成密钥
    decrypted_data = decrypt_data(key)  # 尝试解密
    if decrypted_data:
        root.destroy()
        execute_decrypted(decrypted_data)  # 执行解密后的程序

# 创建美观的解锁界面
root = tk.tk()
root.title("程序解锁")
root.geometry("260x230")
root.resizable(false, false)
root.configure(bg="#f0f0f0")

# 界面组件:图标、输入框、按钮等
icon_label = ttk.label(main_frame, text="🔒", font=("arial", 24))
password_entry = ttk.entry(main_frame, show="*", width=25)
submit_btn = ttk.button(main_frame, text="解锁程序", command=check_password, width=15)
'''

3. 主界面与处理逻辑

def main():
    """主gui界面和处理流程"""
    # 文件选择函数
    def select_exe():
        # 自动设置输出路径
        output_path = os.path.join(dir_name, f"{name_without_ext}_protected.exe")
    
    # 加密处理核心逻辑
    def encrypt():
        # 验证输入
        if not all([exe_path, output_path, password, confirm]):
            messagebox.showerror("错误", "所有字段都必须填写")
            return
        
        # 生成密钥和哈希
        password_hash = hashlib.sha256(password.encode()).hexdigest()
        key = hashlib.sha256(password.encode()).digest()
        
        # 加密文件
        encrypt_file(key, exe_path, encrypted_temp_path)
        
        # 生成stub代码
        stub_code = generate_stub_code(password_hash, encrypted_data_base64)
        
        # pyinstaller打包处理
        pyinstaller_cmd = [
            *find_pyinstaller(),  # 自动检测pyinstaller
            '--onefile', '--noconsole',
            '--name', output_basename,
            *icon_cmd,  # 图标参数
            stub_path
        ]
        
        # 执行打包
        subprocess.run(pyinstaller_cmd, shell=sys.platform.startswith('win'))
        
        # 处理结果
        if os.path.exists(generated_exe):
            shutil.copy(generated_exe, output_path)
            status_label.config(text=f"加密成功! 文件已保存到:\n{output_path}", fg="green")

4. 依赖管理

if __name__ == "__main__":
    # 自动安装缺失依赖
    try:
        from crypto.cipher import aes
    except importerror:
        print("正在安装依赖库pycryptodome...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "pycryptodome"])
        os.execl(sys.executable, sys.executable, *sys.argv)  # 重启脚本
    
    # 检查pyinstaller
    try:
        import pyinstaller
    except importerror:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
    
    main()

三、关键技术概要

1. tkinter运行时修复

def fix_tkinter_runtime():
    """解决pyinstaller打包环境下tkinter的资源路径问题"""
    if getattr(sys, 'frozen', false):
        base_path = sys._meipass
        tk_data_dir = os.path.join(base_path, '_tk_data')
        if not os.path.exists(tk_data_dir):
            tk_data_dir = os.path.join(base_path, 'tk', 'data')
        os.environ['tkdata'] = tk_data_dir

2. 智能pyinstaller检测

def find_pyinstaller():
    """自动检测系统中可用的pyinstaller安装方式"""
    if shutil.which('pyinstaller'):
        return ['pyinstaller']
    
    # 尝试通过python解释器调用
    for py_exe in ['python', 'python3']:
        if shutil.which(py_exe):
            try:
                subprocess.run([py_exe, '-c', 'import pyinstaller'], check=true)
                return [py_exe, '-m', 'pyinstaller']
            except:
                continue
    return none

3. 健壮的错误处理

try:
    # 加密和打包过程
except exception as e:
    error_details = traceback.format_exc()
    messagebox.showerror(
        "错误", 
        f"加密过程中出错:\n\n{str(e)}\n\n"
        f"详细错误信息:\n{error_details[:1000]}"
    )
finally:
    # 确保清理临时文件
    shutil.rmtree(temp_dir, ignore_errors=true)

四、使用说明

主界面功能

  • 选择要加密的exe文件
  • 设置输出路径(自动生成)
  • 添加自定义图标(可选)
  • 设置并确认解锁密码

处理流程

  1. 验证输入信息
  2. 使用aes-256加密原始exe
  3. 生成带gui界面的stub程序
  4. 使用pyinstaller打包成单个exe
  5. 输出保护后的可执行文件

生成的保护程序特点

  • 启动时显示密码输入界面
  • 密码错误时友好提示
  • 验证成功后自动执行原始程序
  • 支持回车键快速提交

五、技术优势

  1. 军事级加密:采用aes-256-cbc加密模式,使用随机初始化向量(iv)
  2. 密码安全:通过sha-256哈希处理密码,不存储明文
  3. 优雅的ui:使用tkinter创建美观的解锁界面
  4. 跨平台兼容:自动处理不同系统的路径问题
  5. 自包含:最终生成单个exe文件,便于分发
  6. 错误恢复:完善的异常处理和临时文件清理

六、总结

这个exe文件加密保护工具集成了现代加密技术和python打包技术,为windows程序提供了简单易用的安全保护方案。通过将商业软件封装到密码保护的gui界面中,开发者可以有效控制软件的分发和使用权限。工具还解决了pyinstaller打包环境下常见的tkinter运行时问题,确保生成的保护程序在各种环境下都能稳定运行。

以上就是使用python实现一个安全封装exe文件加密保护工具的详细内容,更多关于python exe文件加密保护工具的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com