forked from zhangxiaoyang/WechatImageDecoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWechatImageDecoder.py
75 lines (61 loc) · 2.04 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
#!/usr/bin/env python
# zhangxiaoyang.hit[at]gmail.com
import re
class WechatImageDecoder:
def __init__(self, datfile):
datfile = datfile.lower()
decoder = self._match_decoder(datfile)
decoder(datfile)
def _match_decoder(self, datfile):
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, datfile):
return v
return decoders[None]
def _decode_pc_dat(self, datfile):
with open(datfile, 'rb') as f:
buf = bytearray(f.read())
magic = 0xff ^ list(buf)[0] if buf else 0x00
imgfile = re.sub(r'.dat$', '.jpg', datfile)
with open(imgfile, 'wb') as f:
newbuf = bytearray([b ^ magic for b in list(buf)])
f.write(newbuf)
def _decode_android_dat(self, datfile):
with open(datfile, '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' % (datfile, i)
with open(imgfile, 'wb') as f:
f.write(buf[last_index: m.start()])
last_index = m.start()
def _decode_unknown_dat(self, datfile):
raise Exception('Unknown file type')
if __name__ == '__main__':
import sys
if len(sys.argv) != 2:
print('\n'.join([
'Usage:',
' python WechatImageDecoder.py [datfile]',
'',
'Example:',
' # PC:',
' python WechatImageDecoder.py 1234567890.dat',
'',
' # Android:',
' python WechatImageDecoder.py cache.data.10'
]))
sys.exit(1)
_, datfile = sys.argv[:2]
try:
WechatImageDecoder(datfile)
except Exception as e:
print(e)
sys.exit(1)
sys.exit(0)