採用2個手段,小模塊生成pyd,主程序打包時加密
一、python程序打包成pyd
step1:創建新文件test.py
#coding:utf-8
def speak():
print("hello world")
step2:再創建文件setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(name = 'HW',ext_modules = cythonize("test.py"))
step3:執行指令運行setup文件
python setup.py build_ext --inplace
此時生成文件
build
test.c
test.XXXX-XXX.pyd
step4:將test.XXXX-XXX.pyd重命名爲test.pyd(注,一定要與python文件同名)
step5:測試
import test
if __name__=="__main__":
test.speak()
輸出:
hello world
2 pyinstaller打包時
pyinstaller -key 密碼 -Fmain.py
錯誤1:ModuleNotFoundError: No module named 'Crypto.Cipher'
解決:
pip uninstall crypto pycryptodome
pip install pycryptodome
錯誤2:AttributeError: module 'Crypto' has no attribute '__version__'
解決:找到此處,改源碼
File "...\lib\site-packages\PyInstaller\building\makespec.py", line 333, in main
is_version_acceptable = LooseVersion(Crypto.__version__) >= LooseVersion('2.4')
is_version_acceptable = True
錯誤3:TypeError: Object type <class 'str'> cannot be passed to C code
解決:找到此處,改源碼
File "........lib\site-packages\PyInstaller\archive\pyz_crypto.py", line 65, in __create_cipher
return self._aesmod.new(self.key, self._aesmod.MODE_CFB, iv)
... ...
TypeError: Object type <class 'str'> cannot be passed to C code
def __create_cipher(self, iv):
# The 'BlockAlgo' class is stateful, this factory method is used to
# re-initialize the block cipher class with each call to encrypt() and
# decrypt().
print("xws---",type(self.key),self.key)
return self._aesmod.new(self.key.encode("utf-8"), self._aesmod.MODE_CFB, iv)
輸出
xws--- <class 'str'> 000byfwsxnsvrdxs
說明真的是字符串,將self.key按utf-8編碼即可解決問題