aesgcm_decrypt.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import argparse
  2. import urllib.request
  3. from Crypto.Cipher import AES
  4. from os import remove
  5. DESCRIPTION = f"{__file__} - decrypt AES-256-GCM URL"
  6. def read_file(file_path: str):
  7. try:
  8. file = open(file_path, "rb+")
  9. return file.read()
  10. except FileNotFoundError:
  11. print("File not found")
  12. def write_file(file_path: str, data):
  13. try:
  14. file = open(file_path, "wb+")
  15. file.write(data)
  16. except Exception:
  17. print(f"Cannot write file: {file_path}")
  18. def encrypt(key, data):
  19. cipher = AES.new(key, AES.MODE_GCM)
  20. encrypted = cipher.encrypt(data)
  21. return encrypted, cipher.nonce
  22. def decrypt(key, iv, data):
  23. cipher = AES.new(key, AES.MODE_GCM, nonce=iv)
  24. decrypted = cipher.decrypt(data)
  25. return decrypted
  26. def main():
  27. parser = argparse.ArgumentParser(description=DESCRIPTION)
  28. parser.add_argument("url", help="URL with file to decrypt, e.g. aesgcm://download.montague.tld/4a771ac1-f0b2-4a4a-9700-f2a26fa2bb67/tr%C3%A8s%20cool.jpg#8c3d050e9386ec173861778f68e9af38a97aaf82faa4063b4d0878a61261534410c8a84331eaac851759f587")
  29. args = parser.parse_args()
  30. splited_url = args.url.split("#")
  31. download_url = splited_url[0]
  32. download_url = download_url.replace('aesgcm://', 'https://')
  33. splited_download_url = download_url.split('/')
  34. file_name = splited_download_url[len(splited_download_url) - 1]
  35. file_name_enc = f'{file_name}.enc'
  36. # print(f'Downloading {download_url} to {file_name_enc}')
  37. urllib.request.urlretrieve(download_url, file_name_enc)
  38. iv_key = splited_url[1]
  39. iv = iv_key[:24]
  40. key = iv_key[24:]
  41. encrypted_data = read_file(file_name_enc)
  42. iv_b = bytearray.fromhex(iv)
  43. key_b = bytearray.fromhex(key)
  44. decrypted = decrypt(key_b, iv_b, encrypted_data)
  45. write_file(file_name, decrypted)
  46. remove(file_name_enc)
  47. print(file_name)
  48. if __name__ == "__main__":
  49. main()