OpenEncryptedFileRaw.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import win32file, win32api, winerror
  2. import os
  3. def ReadCallback(input_buffer, data, buflen):
  4. fnamein, fnameout, f = data
  5. ## print fnamein, fnameout, buflen
  6. f.write(input_buffer)
  7. ## python 2.3 throws an error if return value is a plain int
  8. return winerror.ERROR_SUCCESS
  9. def WriteCallback(output_buffer, data, buflen):
  10. fnamebackup, fnameout, f = data
  11. file_data=f.read(buflen)
  12. ## returning 0 as len terminates WriteEncryptedFileRaw
  13. output_len=len(file_data)
  14. output_buffer[:output_len]=file_data
  15. return winerror.ERROR_SUCCESS, output_len
  16. tmp_dir=win32api.GetTempPath()
  17. dst_dir=win32api.GetTempFileName(tmp_dir,'oef')[0]
  18. os.remove(dst_dir)
  19. os.mkdir(dst_dir)
  20. print('Destination dir:', dst_dir)
  21. ## create an encrypted file
  22. fname=win32api.GetTempFileName(dst_dir,'ref')[0]
  23. print('orig file:',fname)
  24. f=open(fname,'w')
  25. f.write('xxxxxxxxxxxxxxxx\n'*32768)
  26. f.close()
  27. ## add a couple of extra data streams
  28. f=open(fname+':stream_y','w')
  29. f.write('yyyyyyyyyyyyyyyy\n'*32768)
  30. f.close()
  31. f=open(fname+':stream_z','w')
  32. f.write('zzzzzzzzzzzzzzzz\n'*32768)
  33. f.close()
  34. win32file.EncryptFile(fname)
  35. ## backup raw data of encrypted file
  36. bkup_fname=win32api.GetTempFileName(dst_dir,'bef')[0]
  37. print('backup file:', bkup_fname)
  38. f=open(bkup_fname,'wb')
  39. ctxt=win32file.OpenEncryptedFileRaw(fname,0)
  40. try:
  41. win32file.ReadEncryptedFileRaw(ReadCallback, (fname,bkup_fname,f), ctxt)
  42. finally:
  43. ## if context is not closed, file remains locked even if calling process is killed
  44. win32file.CloseEncryptedFileRaw(ctxt)
  45. f.close()
  46. ## restore data from backup to new encrypted file
  47. dst_fname=win32api.GetTempFileName(dst_dir,'wef')[0]
  48. print('restored file:', dst_fname)
  49. f=open(bkup_fname,'rb')
  50. ctxtout=win32file.OpenEncryptedFileRaw(dst_fname, win32file.CREATE_FOR_IMPORT)
  51. try:
  52. win32file.WriteEncryptedFileRaw(WriteCallback, (bkup_fname,dst_fname,f), ctxtout)
  53. finally:
  54. win32file.CloseEncryptedFileRaw(ctxtout)
  55. f.close()