-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathWechatImageDecoder.py
97 lines (79 loc) · 2.78 KB
/
WechatImageDecoder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env python
# zhangxiaoyang.hit[at]gmail.com
import re
class WechatImageDecoder:
def __init__(self, dat_file):
dat_file = dat_file.lower()
decoder = self._match_decoder(dat_file)
decoder(dat_file)
def _match_decoder(self, dat_file):
decoders = {
r'.+\.dat$': self._decode_pc_dat,
r'cache\.data\.\d+$': self._decode_android_dat,
None: self._decode_unknown_dat,
}
for k, v in decoders.items():
if k is not None and re.match(k, dat_file):
return v
return decoders[None]
def _decode_pc_dat(self, dat_file):
def do_magic(header_code, buf):
return header_code ^ list(buf)[0] if buf else 0x00
def decode(magic, buf):
return bytearray([b ^ magic for b in list(buf)])
def guess_encoding(buf):
headers = {
'jpg': (0xff, 0xd8),
'png': (0x89, 0x50),
'gif': (0x47, 0x49),
}
for encoding in headers:
header_code, check_code = headers[encoding]
magic = do_magic(header_code, buf)
_, code = decode(magic, buf[:2])
if check_code == code:
return (encoding, magic)
print('Decode failed')
sys.exit(1)
with open(dat_file, 'rb') as f:
buf = bytearray(f.read())
file_type, magic = guess_encoding(buf)
img_file = re.sub(r'.dat$', '.' + file_type, dat_file)
with open(img_file, 'wb') as f:
new_buf = decode(magic, buf)
f.write(new_buf)
def _decode_android_dat(self, dat_file):
with open(dat_file, 'rb') as f:
buf = f.read()
last_index = 0
for i, m in enumerate(re.finditer(b'\xff\xd8\xff\xe0\x00\x10\x4a\x46', buf)):
if m.start() == 0:
continue
imgfile = '%s_%d.jpg' % (dat_file, i)
with open(imgfile, 'wb') as f:
f.write(buf[last_index: m.start()])
last_index = m.start()
def _decode_unknown_dat(self, dat_file):
raise Exception('Unknown file type')
if __name__ == '__main__':
import sys
if len(sys.argv) != 2:
print('\n'.join([
'Usage:',
' python WechatImageDecoder.py [dat_file]',
'',
'Example:',
' # PC:',
' python WechatImageDecoder.py 1234567890.dat',
'',
' # Android:',
' python WechatImageDecoder.py cache.data.10'
]))
sys.exit(1)
_, dat_file = sys.argv[:2]
try:
WechatImageDecoder(dat_file)
except Exception as e:
print(e)
sys.exit(1)
sys.exit(0)