bat文件

@echo off
python "python文件绝对路径\文件名.py" & pause

注意:
1)另存为时编码保存为ANSI,防止乱码
2)引号必须是英文引号

tea算法

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TEA/XTEA/XXTEA 解密工具
支持交互式选择算法、自定义DELTA和轮数
"""

import struct


# ==================== 手动修改区域 ====================

# 密钥 (4个32位无符号整数,128位)
KEY = [
0x00010203, # key[0]
0x04050607, # key[1]
0x08090a0b, # key[2]
0x0c0d0e0f, # key[3]
]

# 密文 (32位无符号整数列表,TEA/XTEA固定2个,XXTEA可变长)
# 示例:两个32位整数
CIPHER_TEXT = [
0x12345678, # 密文块1
0x9abcdef0, # 密文块2
]

# 或者使用字节形式输入(会自动转换)
# CIPHER_BYTES = b'\x78\x56\x34\x12\xf0\xde\xbc\x9a' # 小端序示例

# =====================================================


def bytes_to_uint32_list(data):
"""将字节转换为32位无符号整数列表"""
if len(data) % 4 != 0:
# 填充到4字节对齐
data += b'\x00' * (4 - len(data) % 4)
return list(struct.unpack('<' + 'I' * (len(data) // 4), data))


def uint32_list_to_bytes(data):
"""将32位无符号整数列表转换为字节"""
return struct.pack('<' + 'I' * len(data), *data)


def tea_decrypt(cipher, key, delta=0x9e3779b9, rounds=32):
"""
TEA解密算法
cipher: 2个32位无符号整数的列表 [v0, v1]
key: 4个32位无符号整数的列表 [k0, k1, k2, k3]
delta: 魔数,默认0x9e3779b9
rounds: 轮数,默认32
"""
v0, v1 = cipher[0], cipher[1]
k0, k1, k2, k3 = key[0], key[1], key[2], key[3]
sum_val = (delta * rounds) & 0xFFFFFFFF

for _ in range(rounds):
v1 -= ((v0 << 4) + k2) ^ (v0 + sum_val) ^ ((v0 >> 5) + k3)
v1 &= 0xFFFFFFFF
v0 -= ((v1 << 4) + k0) ^ (v1 + sum_val) ^ ((v1 >> 5) + k1)
v0 &= 0xFFFFFFFF
sum_val = (sum_val - delta) & 0xFFFFFFFF

return [v0, v1]


def xtea_decrypt(cipher, key, delta=0x9e3779b9, rounds=32):
"""
XTEA解密算法
cipher: 2个32位无符号整数的列表 [v0, v1]
key: 4个32位无符号整数的列表 [k0, k1, k2, k3]
delta: 魔数,默认0x9e3779b9
rounds: 轮数,默认32
"""
v0, v1 = cipher[0], cipher[1]
sum_val = (delta * rounds) & 0xFFFFFFFF

for _ in range(rounds):
v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum_val + key[(sum_val >> 11) & 3])
v1 &= 0xFFFFFFFF
sum_val = (sum_val - delta) & 0xFFFFFFFF
v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum_val + key[sum_val & 3])
v0 &= 0xFFFFFFFF

return [v0, v1]


def xxtea_decrypt(cipher, key, delta=0x9e3779b9):
"""
XXTEA解密算法
cipher: n个32位无符号整数的列表
key: 4个32位无符号整数的列表
delta: 魔数,默认0x9e3779b9
轮数由数据长度自动计算: rounds = 6 + 52/n
"""
n = len(cipher)
if n < 2:
raise ValueError("XXTEA需要至少2个32位整数")

rounds = 6 + 52 // n
sum_val = (delta * rounds) & 0xFFFFFFFF

y = cipher[0]
for _ in range(rounds):
e = (sum_val >> 2) & 3
for p in range(n - 1, 0, -1):
z = cipher[p - 1]
# MX宏
mx = (((z >> 5) ^ (y << 2)) + ((y >> 3) ^ (z << 4))) ^ ((sum_val ^ y) + (key[(p & 3) ^ e] ^ z))
y = cipher[p] = (cipher[p] - mx) & 0xFFFFFFFF
z = cipher[n - 1]
mx = (((z >> 5) ^ (y << 2)) + ((y >> 3) ^ (z << 4))) ^ ((sum_val ^ y) + (key[(0 & 3) ^ e] ^ z))
y = cipher[0] = (cipher[0] - mx) & 0xFFFFFFFF
sum_val = (sum_val - delta) & 0xFFFFFFFF

return cipher


def print_result(plain, algo_name):
"""打印解密结果"""
print(f"\n{'='*50}")
print(f"{algo_name} 解密结果:")
print(f"{'='*50}")

print("十六进制格式:")
for i, val in enumerate(plain):
print(f" [{i}] 0x{val:08x}")

print("\n十进制格式:")
for i, val in enumerate(plain):
print(f" [{i}] {val}")

# 尝试解释为ASCII字符串
try:
plain_bytes = uint32_list_to_bytes(plain)
print(f"\n字节形式 (hex): {plain_bytes.hex()}")
# 尝试解码为字符串
ascii_str = ''
for b in plain_bytes:
if 32 <= b <= 126:
ascii_str += chr(b)
else:
ascii_str += '.'
print(f"可打印ASCII: {ascii_str}")
except Exception as e:
print(f"转换为字节失败: {e}")

print(f"{'='*50}")


def get_user_input():
"""获取用户输入"""
print("\n" + "="*50)
print("TEA/XTEA/XXTEA 解密工具")
print("="*50)

# 选择算法
print("\n请选择算法:")
print("1. TEA")
print("2. XTEA")
print("3. XXTEA")

while True:
choice = input("输入选择 (1/2/3): ").strip()
if choice in ['1', '2', '3']:
algo_map = {'1': 'TEA', '2': 'XTEA', '3': 'XXTEA'}
algo = algo_map[choice]
break
print("无效选择,请重新输入")

# 设置DELTA
print(f"\n当前默认 DELTA: 0x9e3779b9 ({0x9e3779b9})")
delta_input = input("输入DELTA (十六进制,回车使用默认): ").strip()
if delta_input:
delta = int(delta_input, 16) if delta_input.startswith('0x') else int(delta_input)
else:
delta = 0x9e3779b9

# 设置轮数 (XXTEA不需要)
rounds = 32
if algo != 'XXTEA':
print(f"\n当前默认轮数: 32")
rounds_input = input("输入轮数 (回车使用默认): ").strip()
if rounds_input:
rounds = int(rounds_input)
else:
print(f"\nXXTEA轮数自动计算: 6 + 52/n (n为数据长度)")

return algo, delta, rounds


def main():
"""主函数"""
# 获取用户输入
algo, delta, rounds = get_user_input()

print(f"\n配置信息:")
print(f" 算法: {algo}")
print(f" DELTA: 0x{delta:08x} ({delta})")
if algo != 'XXTEA':
print(f" 轮数: {rounds}")
print(f" 密钥: {[hex(k) for k in KEY]}")
print(f" 密文: {[hex(c) for c in CIPHER_TEXT]}")

# 执行解密
cipher_copy = CIPHER_TEXT.copy()

try:
if algo == 'TEA':
plain = tea_decrypt(cipher_copy, KEY, delta, rounds)
elif algo == 'XTEA':
plain = xtea_decrypt(cipher_copy, KEY, delta, rounds)
elif algo == 'XXTEA':
plain = xxtea_decrypt(cipher_copy, KEY, delta)

print_result(plain, algo)

except Exception as e:
print(f"\n解密失败: {e}")
import traceback
traceback.print_exc()


if __name__ == "__main__":
main()

实现进制与字符串转换的python代码

astart = input('输入待处理数字或字符串:')
#a = int(astart)
bs = input('输入选择:1=数字2=字符串')
b = int(bs)
if b == 1:
c = int(input('数字是1=二进制2=十进制3=十六进制4=八进制'))
if c == 1:
a10 = int(astart,2)
print('转为十进制为:',a10,'\n转为八进制0o为:',oct(a10),'\n转为十六进制0xc为:',hex(a10))
elif c == 2:
a = int(astart)
a10 = a
print('转为二进制0b为:',bin(a),'\n转为八进制0o为:',oct(a),'\n转为十六进制0xc为:',hex(a))
elif c == 3:
a10 = int(astart,16)
print('转为十进制为:',a10,'\n转为八进制0o为:',oct(a10),'\n转为十六进制0xc为:',hex(a10))
elif c == 4:
a10 = int(astart,8)
print('转为十进制为:',a10,'\n转为八进制0o为:',oct(a10),'\n转为十六进制0xc为:',hex(a10))
by = a10.to_bytes((a10.bit_length() + 7) // 8, 'big') # 大端
print('转为字符串为:',by)
elif b == 2:
a2 = astart.encode('utf-8')
a2_10 = int.from_bytes(a2,'big')
print('转为二进制0b为:',bin(a2_10),'\n转为八进制0o为:',oct(a2_10),'\n转为十六进制0xc为:',hex(a2_10),'\n转为十进制为:',a2_10)

换表base64

import base64
import string

str1 = "x2dtJEOmyjacxDemx2eczT5cVS9fVUGvWTuZWjuexjRqy24rV29q"

string1 = "ZYXABCDEFGHIJKLMNOPQRSTUVWzyxabcdefghijklmnopqrstuvw0123456789+/"
string2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

print (base64.b64decode(str1.translate(str.maketrans(string1,string2))))
  • str1是要解密的代码,string1是改过之后的base64表

十六进制倒转脚本

input = open('flag.jpg', 'rb')
input_all = input.read()
ss = input_all[::-1]
output = open('m0re.jpg', 'wb')
output.write(ss)
input.close()
output.close()

端序转换

def swap_groups(b, w):
return b''.join(b[i:i+w][::-1] for i in range(0, len(b), w))

def show(b, w):
out = swap_groups(b, w)
print(f'[{w}] hex:', out.hex())
try:
print(f'[{w}] text:', out.decode('utf-8'))
except:
print(f'[{w}] text:', '(invalid utf-8)')

def main():
while True:
s = input('文本(回车退出): ')
if s == '':
break
raw = s.encode('utf-8')
for w in (1, 2, 3, 4):
show(raw, w)
sel = input('选择字节分组(1-4或正整数,默认1): ').strip()
try:
w = int(sel) if sel else 1
if w <= 0:
w = 1
except:
w = 1
out = swap_groups(raw, w)
print('选定分组:', w)
print('hex:', out.hex())
try:
print('text:', out.decode('utf-8'))
except:
print('text:', '(invalid utf-8)')

if __name__ == '__main__':
main()

CTF千层压缩包终极解压工具

import os
import zipfile
import tarfile
import gzip
import py7zr
import logging
import re
from pathlib import Path

# 配置日志

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class UltimateCTFExtractor:
def __init__(self, max_depth=1000):
self.max_depth = max_depth
self.processed_files = set() # 记录已处理文件的哈希,避免循环

def get_file_signature(self, file_path):
"""通过文件头识别真实压缩格式(不依赖扩展名)"""
try:
with open(file_path, 'rb') as f:
header = f.read(262)

if len(header) < 4:
return "unknown"

# ZIP格式检测
if header.startswith(b'PK'):
return "zip"

# 7z格式检测
if header.startswith(b'7z\xBC\xAF\x27\x1C'):
return "7z"

# GZIP格式检测
if header.startswith(b'\x1F\x8B'):
return "gzip"

# 对于TAR文件,尝试打开验证
try:
with tarfile.open(file_path, 'r:*') as test_tar:
if test_tar.getmembers():
return "tar"
except:
pass

except Exception as e:
logger.error(f"文件格式检测失败: {e}")

return "unknown"

def calculate_file_hash(self, file_path):
"""计算文件哈希,避免重复处理同一文件"""
import hashlib
hasher = hashlib.md5()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest()

def extract_archive(self, file_path, output_dir):
"""解压单个压缩文件"""
file_type = self.get_file_signature(file_path)
filename = os.path.basename(file_path)

logger.info(f"解压: {filename} -> 检测格式: {file_type}")

try:
if file_type == "zip":
with zipfile.ZipFile(file_path, 'r') as zip_ref:
zip_ref.extractall(output_dir)
return True

elif file_type == "7z":
with py7zr.SevenZipFile(file_path, 'r') as sevenz_ref:
sevenz_ref.extractall(output_dir)
return True

elif file_type == "gzip":
# 处理被误改为.tar_gz的.gz文件
if filename.endswith('.tar_gz'):
output_filename = filename.replace('.tar_gz', '')
else:
output_filename = filename[:-3] if filename.endswith('.gz') else filename

output_path = os.path.join(output_dir, output_filename)

with gzip.open(file_path, 'rb') as f_in:
with open(output_path, 'wb') as f_out:
f_out.write(f_in.read())
return True

elif file_type == "tar":
with tarfile.open(file_path, 'r:*') as tar_ref:
tar_ref.extractall(output_dir)
return True

else:
logger.warning(f"未知或不支持的格式,可能是最终文件: {filename}")
return False

except Exception as e:
logger.error(f"解压失败 {filename}: {e}")
return False

def find_compressed_files(self, directory):
"""在目录中查找所有压缩文件"""
compressed_files = []

for item in os.listdir(directory):
item_path = os.path.join(directory, item)
if os.path.isfile(item_path) and self.get_file_signature(item_path) != "unknown":
compressed_files.append(item_path)

return compressed_files

def auto_extract_all(self, start_file_path, final_output_dir=None):
"""自动解压所有层的核心函数"""
if final_output_dir is None:
final_output_dir = "ctf_final_result"

# 创建输出目录
os.makedirs(final_output_dir, exist_ok=True)

# 使用队列来管理待解压文件
from collections import deque
queue = deque([(start_file_path, final_output_dir, 0)]) # (文件路径, 输出目录, 当前深度)

total_extracted = 0

logger.info("🚀 开始自动解压千层压缩包...")
logger.info(f"起始文件: {os.path.basename(start_file_path)}")
logger.info(f"最终输出目录: {final_output_dir}")
print("=" * 60)

while queue:
current_file, output_dir, current_depth = queue.popleft()

if current_depth >= self.max_depth:
logger.warning(f"达到最大深度限制 {self.max_depth}")
break

# 检查文件是否存在
if not os.path.exists(current_file):
logger.error(f"文件不存在: {current_file}")
continue

# 计算文件哈希,避免重复处理
file_hash = self.calculate_file_hash(current_file)
if file_hash in self.processed_files:
logger.info(f"跳过已处理文件: {os.path.basename(current_file)}")
continue

self.processed_files.add(file_hash)

# 解压当前文件
logger.info(f"[深度 {current_depth}] 处理: {os.path.basename(current_file)}")

success = self.extract_archive(current_file, output_dir)

if success:
total_extracted += 1

# 查找新生成的压缩文件
new_compressed_files = self.find_compressed_files(output_dir)

# 将新找到的压缩文件加入队列
for new_file in new_compressed_files:
queue.append((new_file, output_dir, current_depth + 1))

# 可选:解压后删除原压缩文件以节省空间
# try:
# os.remove(current_file)
# logger.info(f"已删除原文件: {os.path.basename(current_file)}")
# except:
# pass

# 显示进度
if current_depth % 10 == 0:
logger.info(f"进度: 已处理 {total_extracted} 个压缩包,当前深度: {current_depth}")

else:
logger.warning(f"解压失败或到达最终文件: {os.path.basename(current_file)}")

# 解压完成,查找最终文件
logger.info("=" * 60)
logger.info("✅ 自动解压过程完成!")
logger.info(f"总共处理了 {total_extracted} 个压缩包")

# 查找并显示最终的非压缩文件
final_files = self.find_final_files(final_output_dir)
if final_files:
logger.info("🎉 找到最终文件:")
for file_path in final_files:
file_size = os.path.getsize(file_path)
logger.info(f" 📄 {os.path.basename(file_path)} (大小: {file_size} 字节)")
logger.info(f" 路径: {file_path}")
else:
logger.info("未找到明显的最终文件,请检查输出目录")

return True

def find_final_files(self, directory):
"""查找非压缩的最终文件"""
final_files = []

for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
if self.get_file_signature(file_path) == "unknown": # 非压缩文件
final_files.append(file_path)

return final_files

def main():
"""主函数 - 一键解压您的千层压缩包"""

# 您的文件路径
start_file = r"G:\ctf\nss\Misc\layer_227.tar_gz"

# 检查文件是否存在
if not os.path.exists(start_file):
logger.error(f"文件不存在: {start_file}")
print("请检查文件路径是否正确")
return

# 创建解压器并开始自动解压
extractor = UltimateCTFExtractor(max_depth=1000)

print("🔍 CTF千层压缩包终极解压工具")
print("=" * 50)

try:
extractor.auto_extract_all(start_file, "ctf_final_result_all_layers")
print("🎊 所有层级解压完成!")
except KeyboardInterrupt:
print("⏹️ 用户中断了解压过程")
except Exception as e:
logger.error(f"解压过程中出现错误: {e}")
print("❌ 解压失败,请检查错误信息")

if __name__ == "__main__":
main()

base64隐写脚本

import base64

def Base64Stego_Decrypt(LineList):
Base64Char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" #Base64字符集 已按照规范排列
BinaryText = ""
for line in LineList:
if line.find("==") > 0: #如果文本中有2个=符号
temp = bin(Base64Char.find(line[-3]) & 15)[2:] #通过按位与&15运算取出二进制数后4位 [2:]的作用是将0b过滤掉
BinaryText = BinaryText+"0"*(4-len(temp))+temp #高位补0
elif line.find("=") > 0: #如果文本中有1个=符号
temp = bin(Base64Char.find(line[-2]) & 3)[2:] #通过按位与&3运算取出二进制数后2位
BinaryText = BinaryText+"0"*(2-len(temp))+temp #高位补0
Text = ""
if(len(BinaryText) % 8 != 0): #最终得到的隐写数据二进制位数不一定都是8的倍数,为了避免数组越界,加上一个判断
print("警告:二进制文本位数有误,将进行不完整解析。")
for i in range(0, len(BinaryText), 8):
if(i+8 > len(BinaryText)):
Text = Text+"-"+BinaryText[i:]
return Text
else:
Text = Text+chr(int(BinaryText[i:i+8], 2))
else:
for i in range(0, len(BinaryText), 8):
Text = Text+chr(int(BinaryText[i:i+8], 2)) #将得到的二进制数每8位一组对照ASCII码转化字符
return Text

def Base64_ForString_Decrypt(Text): #Base64解密
try:
DecryptedText = str(Text).encode("utf-8")
DecryptedText = base64.b64decode(DecryptedText)
DecryptedText = DecryptedText.decode("utf-8")
except:
return 0
return DecryptedText

if __name__ == "__main__":
Course = input("文件名:")
File = open(Course, "r")
LineList = File.read().splitlines()
print("显式内容为:")
for line in LineList:
print(Base64_ForString_Decrypt(line),end="")
print("隐写内容为:")
print(Base64Stego_Decrypt(LineList))

pyc识别python版本

import struct

PYTHON_MAGIC = {
# Python 1
20121: (1, 5),
50428: (1, 6),

# Python 2
50823: (2, 0),
60202: (2, 1),
60717: (2, 2),
62011: (2, 3), # a0
62021: (2, 3), # a0
62041: (2, 4), # a0
62051: (2, 4), # a3
62061: (2, 4), # b1
62071: (2, 5), # a0
62081: (2, 5), # a0
62091: (2, 5), # a0
62092: (2, 5), # a0
62101: (2, 5), # b3
62111: (2, 5), # b3
62121: (2, 5), # c1
62131: (2, 5), # c2
62151: (2, 6), # a0
62161: (2, 6), # a1
62171: (2, 7), # a0
62181: (2, 7), # a0
62191: (2, 7), # a0
62201: (2, 7), # a0
62211: (2, 7), # a0

# Python 3
3000: (3, 0),
3010: (3, 0),
3020: (3, 0),
3030: (3, 0),
3040: (3, 0),
3050: (3, 0),
3060: (3, 0),
3061: (3, 0),
3071: (3, 0),
3081: (3, 0),
3091: (3, 0),
3101: (3, 0),
3103: (3, 0),
3111: (3, 0), # a4
3131: (3, 0), # a5

# Python 3.1
3141: (3, 1), # a0
3151: (3, 1), # a0

# Python 3.2
3160: (3, 2), # a0
3170: (3, 2), # a1
3180: (3, 2), # a2

# Python 3.3
3190: (3, 3), # a0
3200: (3, 3), # a0
3220: (3, 3), # a1
3230: (3, 3), # a4

# Python 3.4
3250: (3, 4), # a1
3260: (3, 4), # a1
3270: (3, 4), # a1
3280: (3, 4), # a1
3290: (3, 4), # a4
3300: (3, 4), # a4
3310: (3, 4), # rc2

# Python 3.5
3320: (3, 5), # a0
3330: (3, 5), # b1
3340: (3, 5), # b2
3350: (3, 5), # b2
3351: (3, 5), # 3.5.2

# Python 3.6
3360: (3, 6), # a0
3361: (3, 6), # a0
3370: (3, 6), # a1
3371: (3, 6), # a1
3372: (3, 6), # a1
3373: (3, 6), # b1
3375: (3, 6), # b1
3376: (3, 6), # b1
3377: (3, 6), # b1
3378: (3, 6), # b2
3379: (3, 6), # rc1

# Python 3.7
3390: (3, 7), # a1
3391: (3, 7), # a2
3392: (3, 7), # a4
3393: (3, 7), # b1
3394: (3, 7), # b5

# Python 3.8
3400: (3, 8), # a1
3401: (3, 8), # a1
3410: (3, 8), # a1
3411: (3, 8), # b2
3412: (3, 8), # b2
3413: (3, 8), # b4

# Python 3.9
3420: (3, 9), # a0
3421: (3, 9), # a0
3422: (3, 9), # a0
3423: (3, 9), # a2
3424: (3, 9), # a2
3425: (3, 9), # a2

# Python 3.10
3430: (3, 10), # a1
3431: (3, 10), # a1
3432: (3, 10), # a2
3433: (3, 10), # a2
3434: (3, 10), # a6
3435: (3, 10), # a7
3436: (3, 10), # b1
3437: (3, 10), # b1
3438: (3, 10), # b1
3439: (3, 10), # b1

# Python 3.11
3450: (3, 11), # a1
3451: (3, 11), # a1
3452: (3, 11), # a1
3453: (3, 11), # a1
3454: (3, 11), # a1
3455: (3, 11), # a1
3456: (3, 11), # a1
3457: (3, 11), # a1
3458: (3, 11), # a1
3459: (3, 11), # a1
3460: (3, 11), # a1
3461: (3, 11), # a2
3462: (3, 11), # a3
3463: (3, 11), # a3
3464: (3, 11), # a3
3465: (3, 11), # a3
3466: (3, 11), # a4
3467: (3, 11), # a4
3468: (3, 11), # a4
3469: (3, 11), # a4
3470: (3, 11), # a4
3471: (3, 11), # a4
3472: (3, 11), # a4
3473: (3, 11), # a4
3474: (3, 11), # a4
3475: (3, 11), # a5
3476: (3, 11), # a5
3477: (3, 11), # a5
3478: (3, 11), # a5
3479: (3, 11), # a5
3480: (3, 11), # a5
3481: (3, 11), # a5
3482: (3, 11), # a5
3483: (3, 11), # a5
3484: (3, 11), # a5
3485: (3, 11), # a5
3486: (3, 11), # a6
3487: (3, 11), # a6
3488: (3, 11), # a6
3489: (3, 11), # a6
3490: (3, 11), # a6
3491: (3, 11), # a6
3492: (3, 11), # a7
3493: (3, 11), # a7
3494: (3, 11), # a7
3495: (3, 11), # b4

# Python 3.12
3500: (3, 12), # a1
3501: (3, 12), # a1
3502: (3, 12), # a1
3503: (3, 12), # a1
3504: (3, 12), # a1
3505: (3, 12), # a1
3506: (3, 12), # a1
3507: (3, 12), # a1
3508: (3, 12), # a1
3509: (3, 12), # a1
3510: (3, 12), # a2
3511: (3, 12), # a2
3512: (3, 12), # a2
3513: (3, 12), # a4
3514: (3, 12), # a4
3515: (3, 12), # a5
3516: (3, 12), # a5
3517: (3, 12), # a5
3518: (3, 12), # a6
3519: (3, 12), # a6
3520: (3, 12), # a6
3521: (3, 12), # a7
3522: (3, 12), # a7
3523: (3, 12), # a7
3524: (3, 12), # a7
3525: (3, 12), # b1
3526: (3, 12), # b1
3527: (3, 12), # b1
3528: (3, 12), # b1
3529: (3, 12), # b1
3530: (3, 12), # b1
3531: (3, 12), # b1
}


def magic_word_to_version(magic_word):
if not isinstance(magic_word, int):
magic_word = struct.unpack("<H", magic_word)[0]
return PYTHON_MAGIC[magic_word]


def pyc_file_to_magic_word(pyc_file):
with open(pyc_file, 'rb') as f:
magic = f.read(4)
magic_word = int.from_bytes(magic[:2], 'little')
return magic_word

file = input("请输入文件路径:")
magic_number = pyc_file_to_magic_word(file)
python_version = magic_word_to_version(magic_number)
print(python_version)

rc4

# rc4_decrypt.py
def rc4(key, data):
"""RC4加密/解密(对称算法)"""
S = list(range(256))
j = 0

# KSA
for i in range(256):
j = (j + S[i] + key[i % len(key)]) % 256
S[i], S[j] = S[j], S[i]

# PRGA
i = j = 0
result = []

for byte in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
k = S[(S[i] + S[j]) % 256]
result.append(byte ^ k)

return bytes(result)


# 密钥
key = b"ISCTF2025"

# 密文(从IDA中获取的25字节)
ciphertext = bytes([
0x1D, 0xD5, 0x38, 0x33, 0xAF, 0xB5, 0x51, 0xF3, 0x2C, 0x6B,
0x6E, 0xFE, 0x41, 0x24, 0x43, 0xD2, 0x71, 0xCF, 0xA4, 0x4C,
0xE3, 0x9A, 0x9A, 0xB5, 0x31
])

print(f"密钥: {key}")
print(f"密钥长度: {len(key)}")
print(f"密文 (hex): {ciphertext.hex()}")
print(f"密文长度: {len(ciphertext)}")

# RC4解密(加密和解密是相同的操作)
plaintext = rc4(key, ciphertext)
print(f"\n解密结果 (原始字节): {plaintext}")
print(f"解密结果 (hex): {plaintext.hex()}")

# 尝试解码为字符串
try:
print(f"解密结果 (ASCII): {plaintext.decode('ascii')}")
except:
print("解密结果不是纯ASCII")

# 如果包含不可打印字符,显示所有表示
print("\n字符分析:")
for i, byte in enumerate(plaintext):
if 32 <= byte <= 126: # 可打印ASCII
print(f" [{i:2}] 0x{byte:02x} = '{chr(byte)}'")
else:
print(f" [{i:2}] 0x{byte:02x} = 不可打印")

# 检查是否是flag格式
if plaintext.startswith(b'flag{') and plaintext.endswith(b'}'):
print(f"\n!!! 找到flag: {plaintext.decode('ascii')}")
elif b'flag{' in plaintext:
# 搜索可能的flag
import re

matches = re.findall(b'flag\{[^}]*\}', plaintext)
for match in matches:
print(f"\n!!! 找到flag: {match.decode('ascii')}")