forked from mhammond/pywin32
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenEncryptedFileRaw.py
More file actions
63 lines (53 loc) · 1.92 KB
/
OpenEncryptedFileRaw.py
File metadata and controls
63 lines (53 loc) · 1.92 KB
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
import os
import win32api
import win32file
import winerror
def ReadCallback(input_buffer, data, buflen):
fnamein, fnameout, f = data
# print(fnamein, fnameout, buflen)
f.write(input_buffer)
return winerror.ERROR_SUCCESS
def WriteCallback(output_buffer, data, buflen):
fnamebackup, fnameout, f = data
file_data = f.read(buflen)
## returning 0 as len terminates WriteEncryptedFileRaw
output_len = len(file_data)
output_buffer[:output_len] = file_data
return winerror.ERROR_SUCCESS, output_len
tmp_dir = win32api.GetTempPath()
dst_dir = win32api.GetTempFileName(tmp_dir, "oef")[0]
os.remove(dst_dir)
os.mkdir(dst_dir)
print("Destination dir:", dst_dir)
## create an encrypted file
fname = win32api.GetTempFileName(dst_dir, "ref")[0]
print("orig file:", fname)
with open(fname, "w") as f:
f.write("xxxxxxxxxxxxxxxx\n" * 32768)
## add a couple of extra data streams
with open(fname + ":stream_y", "w") as f:
f.write("yyyyyyyyyyyyyyyy\n" * 32768)
with open(fname + ":stream_z", "w") as f:
f.write("zzzzzzzzzzzzzzzz\n" * 32768)
win32file.EncryptFile(fname)
## backup raw data of encrypted file
bkup_fname = win32api.GetTempFileName(dst_dir, "bef")[0]
print("backup file:", bkup_fname)
fw = open(bkup_fname, "wb")
ctxt = win32file.OpenEncryptedFileRaw(fname, 0)
try:
win32file.ReadEncryptedFileRaw(ReadCallback, (fname, bkup_fname, fw), ctxt)
finally:
## if context is not closed, file remains locked even if calling process is killed
win32file.CloseEncryptedFileRaw(ctxt)
fw.close()
## restore data from backup to new encrypted file
dst_fname = win32api.GetTempFileName(dst_dir, "wef")[0]
print("restored file:", dst_fname)
fr = open(bkup_fname, "rb")
ctxtout = win32file.OpenEncryptedFileRaw(dst_fname, win32file.CREATE_FOR_IMPORT)
try:
win32file.WriteEncryptedFileRaw(WriteCallback, (bkup_fname, dst_fname, fr), ctxtout)
finally:
win32file.CloseEncryptedFileRaw(ctxtout)
fr.close()