import os
import time
import win32file
import win32con
import pywintypes
def detect_key(dat_content):
"""
通过分析文件内容自动检测密钥
"""
# 常见的图片文件头
common_headers = {
b'\xFF\xD8': 'jpg', # JPEG 文件头
b'\x89\x50': 'png', # PNG 文件头
b'\x47\x49': 'gif', # GIF 文件头
b'\x42\x4D': 'bmp', # BMP 文件头
}
for key in range(256): # 尝试所有可能的密钥 (0-255)
decrypted_data = bytes([byte ^ key for byte in dat_content[:2]]) # 只解密前两个字节
for header, format_name in common_headers.items():
if decrypted_data.startswith(header):
return key, format_name
return None, None
def set_file_creation_time(file_path, creation_time):
"""
使用 pywin32 设置文件的创建时间
"""
# 将时间戳转换为 pywintypes 时间对象
win_time = pywintypes.Time(creation_time)
# 打开文件句柄
handle = win32file.CreateFile(
file_path,
win32con.GENERIC_WRITE,
0,
None,
win32con.OPEN_EXISTING,
0,
None
)
# 设置文件的创建时间
win32file.SetFileTime(handle, win_time, None, None)
win32file.CloseHandle(handle)
def decode_wechat_image(dat_file, output_folder):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 获取原文件的创建时间
creation_time = os.path.getctime(dat_file)
with open(dat_file, 'rb') as f:
dat_content = f.read()
# 获取文件名的前缀
file_name = os.path.basename(dat_file).split('.')[0]
# 自动检测密钥
key, image_format = detect_key(dat_content)
if key is None:
print(f"无法检测到密钥或识别图片格式: {dat_file}")
return
# 解密并保存图片
decrypted_data = bytes([byte ^ key for byte in dat_content])
output_file = os.path.join(output_folder, f"{file_name}.{image_format}")
with open(output_file, 'wb') as f:
f.write(decrypted_data)
# 设置新文件的创建时间为原文件的创建时间
set_file_creation_time(output_file, creation_time)
print(f"图片已保存到: {output_file} (创建时间已保留)")
def batch_decode_wechat_images(input_folder, output_folder):
for root, dirs, files in os.walk(input_folder):
for file in files:
if file.endswith('.dat'):
dat_file = os.path.join(root, file)
decode_wechat_image(dat_file, output_folder)
if __name__ == "__main__":
input_folder = r'C:\Users\yangy\Documents\WeChat Files\wxid_4ipvtcu7uzyk12\FileStorage\MsgAttach\454fe72042640d5aaed6d8b2aa470459\Thumb\2025-03'
output_folder = r'E:\微信捕捉\weixin捕捉\jiemi\图片2'
batch_decode_wechat_images(input_folder, output_folder)