PyInstaller spec文件cipher选项作用及Python代码加密实现方法
PyInstaller加密打包问题解答
环境信息
- Python 3.11.1
- PyInstaller 5.7.0
- Mac Ventura 13.2
- 使用PyCharm虚拟环境,计划编写
.spec文件打包单文件夹程序并加密,因直接给cipher参数传字符串/字节出现AttributeError报错。
1. cipher选项的作用是什么?
cipher是PyInstaller用于加密打包后字节码的参数,它需要接收一个标准加密对象(而非普通字符串或字节)。其核心作用是将编译后的.pyc文件转换为加密的.pyz格式,提升源码被反编译的门槛——如果不配置该参数,PyInstaller仅会将源码编译为未加密的字节码,很容易被反编译工具还原出原始逻辑。
2. 如何通过PyInstaller实现Python代码加密?
步骤1:生成合法的block_cipher对象
不能直接传字符串/字节,需用PyInstaller兼容的AES加密对象。在.spec文件开头添加以下代码:
from Crypto.Cipher import AES # 密钥长度必须是16、24或32字节(对应AES-128/192/256加密强度) key = b'your_16_byte_secret_key' # 示例:16字节密钥 block_cipher = AES.new(key, AES.MODE_EAX)
步骤2:在.spec文件中配置cipher参数
将生成的block_cipher传入Analysis和PYZ模块的cipher参数,完整.spec示例结构如下:
from Crypto.Cipher import AES block_cipher = AES.new(b'your_16_byte_secret_key', AES.MODE_EAX) a = Analysis( ['main.py'], # 你的主脚本路径 pathex=['/path/to/your/project'], binaries=[], datas=[], hiddenimports=[], hookspath=[], excludes=[], cipher=block_cipher, # 配置加密对象 ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) # PYZ部分也要传入 exe = EXE( pyz, a.scripts, a.binaries, a.zipfiles, a.datas, name='your_app', console=True, # GUI程序改为False upx=True )
步骤3:执行打包命令
直接运行以下命令完成加密打包:
pyinstaller your_script.spec
注意事项
- 密钥长度必须严格为16、24或32字节,否则会触发加密算法报错。
- 这种加密仅能提高反编译门槛,无法做到绝对安全,核心敏感逻辑建议结合C扩展等方式进一步加固。
内容的提问来源于stack exchange,提问作者체라치에
相关产品推荐
相关产品推荐

