在反編譯python生成可執行文件exe時,引用的類庫文件經常遇到使用Crypto 模塊AES算法加密,解包生成的並不是pyc文件,而是加密的pyc. encrypted文件,當然它也無法查看編譯。當然,它也是可以解密的。
解密流程
第一步,獲取Crypto 的key,這是打包時由開發者指定的。解包完成后將在根目錄形成名為"pyimod00_crypto_key.pyc"的文件,將它轉為py文件即可查看key文件;
第二步,編寫解密處理的腳本代碼
import glob
import zlib
import tinyaes
from pathlib import Path
CRYPT_BLOCK_SIZE = 16
# key obtained from pyimod00_crypto_key
key = bytes('MySup3rS3cr3tK3y', 'utf-8')
for p in Path("PYZ-00.pyz_extracted").glob("**/*.pyc.encrypted"):
inf = open(p, 'rb') # encrypted file input
outf = open(p.with_name(p.stem), 'wb') # output file
# Initialization vector
iv = inf.read(CRYPT_BLOCK_SIZE)
cipher = tinyaes.AES(key, iv)
# Decrypt and decompress
plaintext = zlib.decompress(cipher.CTR_xcrypt_buffer(inf.read()))
# Write pyc header
# The header below is for Python 3.8
outf.write(b'\x55\x0d\x0d\x0a\0\0\0\0\0\0\0\0\0\0\0\0')
# Write decrypted data
outf.write(plaintext)
inf.close()
outf.close()
# Delete .pyc.encrypted file
p.unlink()
在前一步中獲取的key是必須文件,否則無法進行解密;對於不同pyton版本頭文件(header)也不相同,2.7~3.10如下所示:
Python 2.7: \x03\xf3\x0d\x0a\0\0\0\0
Python 3.0: \x3b\x0c\x0d\x0a\0\0\0\0
Python 3.1: \x4f\x0c\x0d\x0a\0\0\0\0
Python 3.2: \x6c\x0c\x0d\x0a\0\0\0\0
Python 3.3: \x9e\x0c\x0d\x0a\0\0\0\0\0\0\0\0
Python 3.4: \xee\x0c\x0d\x0a\0\0\0\0\0\0\0\0
Python 3.5: \x17\x0d\x0d\x0a\0\0\0\0\0\0\0\0
Python 3.6: \x33\x0d\x0d\x0a\0\0\0\0\0\0\0\0
Python 3.7: \x42\x0d\x0d\x0a\0\0\0\0\0\0\0\0\0\0\0\0
Python 3.8: \x55\x0d\x0d\x0a\0\0\0\0\0\0\0\0\0\0\0\0
Python 3.9: \x61\x0d\x0d\x0a\0\0\0\0\0\0\0\0\0\0\0\0
Python 3.10: \x6f\x0d\x0d\x0a\0\0\0\0\0\0\0\0\0\0\0\0
第三步,執行腳本文件,即可將加密的pyc. encrypted文件轉成不加密的pyc文件。
參考資料
Frequently Asked Questions · extremecoders-re/pyinstxtractor Wiki · GitHub
