使用Python實(shí)現(xiàn)一個(gè)安全封裝EXE文件加密保護(hù)工具
一、概述
這個(gè)Python腳本實(shí)現(xiàn)了一個(gè)強(qiáng)大的EXE文件加密保護(hù)工具,它能夠?qū)⑷魏蜽indows可執(zhí)行文件封裝到一個(gè)帶密碼保護(hù)的GUI程序中。核心功能包括:
- 使用AES-256加密算法保護(hù)原始EXE文件
- 創(chuàng)建美觀的密碼驗(yàn)證界面
- 支持自定義程序圖標(biāo)
- 自動(dòng)處理PyInstaller打包過(guò)程
- 修復(fù)Tkinter在打包環(huán)境中的運(yùn)行時(shí)問(wèn)題
二、核心功能模塊
1. 文件加密模塊
def encrypt_file(key, in_path, out_path):
"""使用AES-256 CBC模式加密文件"""
iv = get_random_bytes(16) # 生成隨機(jī)初始化向量
cipher = AES.new(key, AES.MODE_CBC, iv) # 創(chuàng)建加密器
with open(in_path, 'rb') as f_in:
data = f_in.read() # 讀取原始文件內(nèi)容
# 加密并填充數(shù)據(jù)
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) # 寫(xiě)入加密文件2. Stub程序生成器
這是加密后的EXE文件運(yùn)行時(shí)顯示的解鎖界面核心代碼:
def generate_stub_code(password_hash, encrypted_data_base64):
"""生成包含密碼驗(yàn)證界面的Python代碼"""
return f'''#!/usr/bin/env python
# Tkinter運(yùn)行時(shí)修復(fù) - 解決打包環(huán)境下的關(guān)鍵問(wèn)題
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 # 設(shè)置環(huán)境變量
# 在創(chuàng)建Tkinter界面之前調(diào)用修復(fù)函數(shù)
fix_tkinter_runtime()
# 密碼驗(yàn)證邏輯
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) # 執(zhí)行解密后的程序
# 創(chuàng)建美觀的解鎖界面
root = tk.Tk()
root.title("程序解鎖")
root.geometry("260x230")
root.resizable(False, False)
root.configure(bg="#f0f0f0")
# 界面組件:圖標(biāo)、輸入框、按鈕等
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界面和處理流程"""
# 文件選擇函數(shù)
def select_exe():
# 自動(dòng)設(shè)置輸出路徑
output_path = os.path.join(dir_name, f"{name_without_ext}_protected.exe")
# 加密處理核心邏輯
def encrypt():
# 驗(yàn)證輸入
if not all([exe_path, output_path, password, confirm]):
messagebox.showerror("錯(cuò)誤", "所有字段都必須填寫(xiě)")
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(), # 自動(dòng)檢測(cè)PyInstaller
'--onefile', '--noconsole',
'--name', output_basename,
*icon_cmd, # 圖標(biāo)參數(shù)
stub_path
]
# 執(zhí)行打包
subprocess.run(pyinstaller_cmd, shell=sys.platform.startswith('win'))
# 處理結(jié)果
if os.path.exists(generated_exe):
shutil.copy(generated_exe, output_path)
status_label.config(text=f"加密成功! 文件已保存到:\n{output_path}", fg="green")4. 依賴(lài)管理
if __name__ == "__main__":
# 自動(dòng)安裝缺失依賴(lài)
try:
from Crypto.Cipher import AES
except ImportError:
print("正在安裝依賴(lài)庫(kù)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()三、關(guān)鍵技術(shù)概要
1. Tkinter運(yùn)行時(shí)修復(fù)
def fix_tkinter_runtime():
"""解決PyInstaller打包環(huán)境下Tkinter的資源路徑問(wèn)題"""
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_dir2. 智能PyInstaller檢測(cè)
def find_pyinstaller():
"""自動(dòng)檢測(cè)系統(tǒng)中可用的PyInstaller安裝方式"""
if shutil.which('pyinstaller'):
return ['pyinstaller']
# 嘗試通過(guò)Python解釋器調(diào)用
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 None3. 健壯的錯(cuò)誤處理
try:
# 加密和打包過(guò)程
except Exception as e:
error_details = traceback.format_exc()
messagebox.showerror(
"錯(cuò)誤",
f"加密過(guò)程中出錯(cuò):\n\n{str(e)}\n\n"
f"詳細(xì)錯(cuò)誤信息:\n{error_details[:1000]}"
)
finally:
# 確保清理臨時(shí)文件
shutil.rmtree(temp_dir, ignore_errors=True)四、使用說(shuō)明
主界面功能:
- 選擇要加密的EXE文件
- 設(shè)置輸出路徑(自動(dòng)生成)
- 添加自定義圖標(biāo)(可選)
- 設(shè)置并確認(rèn)解鎖密碼
處理流程:
- 驗(yàn)證輸入信息
- 使用AES-256加密原始EXE
- 生成帶GUI界面的stub程序
- 使用PyInstaller打包成單個(gè)EXE
- 輸出保護(hù)后的可執(zhí)行文件
生成的保護(hù)程序特點(diǎn):
- 啟動(dòng)時(shí)顯示密碼輸入界面
- 密碼錯(cuò)誤時(shí)友好提示
- 驗(yàn)證成功后自動(dòng)執(zhí)行原始程序
- 支持回車(chē)鍵快速提交
五、技術(shù)優(yōu)勢(shì)
- 軍事級(jí)加密:采用AES-256-CBC加密模式,使用隨機(jī)初始化向量(IV)
- 密碼安全:通過(guò)SHA-256哈希處理密碼,不存儲(chǔ)明文
- 優(yōu)雅的UI:使用Tkinter創(chuàng)建美觀的解鎖界面
- 跨平臺(tái)兼容:自動(dòng)處理不同系統(tǒng)的路徑問(wèn)題
- 自包含:最終生成單個(gè)EXE文件,便于分發(fā)
- 錯(cuò)誤恢復(fù):完善的異常處理和臨時(shí)文件清理
六、總結(jié)
這個(gè)EXE文件加密保護(hù)工具集成了現(xiàn)代加密技術(shù)和Python打包技術(shù),為Windows程序提供了簡(jiǎn)單易用的安全保護(hù)方案。通過(guò)將商業(yè)軟件封裝到密碼保護(hù)的GUI界面中,開(kāi)發(fā)者可以有效控制軟件的分發(fā)和使用權(quán)限。工具還解決了PyInstaller打包環(huán)境下常見(jiàn)的Tkinter運(yùn)行時(shí)問(wèn)題,確保生成的保護(hù)程序在各種環(huán)境下都能穩(wěn)定運(yùn)行。
以上就是使用Python實(shí)現(xiàn)一個(gè)安全封裝EXE文件加密保護(hù)工具的詳細(xì)內(nèi)容,更多關(guān)于Python EXE文件加密保護(hù)工具的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- python環(huán)境功能強(qiáng)大的pip-audit安全漏洞掃描工具
- Python操作sqlite3快速、安全插入數(shù)據(jù)(防注入)的實(shí)例
- Python線程之線程安全的隊(duì)列Queue
- 詳細(xì)總結(jié)Python常見(jiàn)的安全問(wèn)題
- Python?Bleach保障網(wǎng)絡(luò)安全防止網(wǎng)站受到XSS(跨站腳本)攻擊
- python 安全地刪除列表元素的方法
- Python從零打造高安全密碼管理器
- Python hashlib庫(kù)數(shù)據(jù)安全加密必備指南
- Python實(shí)現(xiàn)安全密碼生成器的示例代碼
- Python如何保護(hù)代碼和數(shù)據(jù),常見(jiàn)的安全漏洞及應(yīng)對(duì)措施有哪些?
相關(guān)文章
淺談cv2.imread()和keras.preprocessing中的image.load_img()區(qū)別
這篇文章主要介紹了淺談cv2.imread()和keras.preprocessing中的image.load_img()區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Python中import的用法陷阱解決盤(pán)點(diǎn)小結(jié)
這篇文章主要為大家介紹了Python中import的用法陷阱解決盤(pán)點(diǎn)小結(jié),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10
Django def clean()函數(shù)對(duì)表單中的數(shù)據(jù)進(jìn)行驗(yàn)證操作
這篇文章主要介紹了Django def clean()函數(shù)對(duì)表單中的數(shù)據(jù)進(jìn)行驗(yàn)證操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
基于keras中import keras.backend as K的含義說(shuō)明
這篇文章主要介紹了keras中import keras.backend as K的含義說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05
pandas實(shí)現(xiàn)將日期轉(zhuǎn)換成timestamp
今天小編就為大家分享一篇pandas實(shí)現(xiàn)將日期轉(zhuǎn)換成timestamp,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
詳解Python 多線程 Timer定時(shí)器/延遲執(zhí)行、Event事件
這篇文章主要介紹了Python 多線程 Timer定時(shí)器/延遲執(zhí)行、Event事件的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-06-06

