Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OpenEncryptedFileRaw.py 2.0KB

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