import requests import subprocess import gzip import urllib.request import sys import base64 # Variables of the needed elements extract_id = sys.argv[2] # auth_token = sys.argv[3] base_url = "https://analytics.northpass.io/extracts" encryption_key = sys.argv[3] current_dir = "./" # Set the API endpoint, authentication headers, and other parameters headers = { "accept": "application/json", "X-Api-Key": sys.argv[1], } # This first call provides you with the fileID and IV value to download the encrypted file def get_extract_id(base_url, headers, extract_id, encryption_key): url = f"{base_url}/{extract_id}/files/latest/" response = requests.get(url, headers=headers) data = response.json() file_id = data["fileId"] iv = data["initializationVector"] download_file(base_url, headers, extract_id, file_id, encryption_key, iv) # This function downloads the file, changes the IV and EK from base64 to Hex, and then decrypts it. # It then opens and prints the results for verification that the data is human readable. def download_file(base_url, headers, extract_id, file_id, encryption_key, iv): url = f"{base_url}/{extract_id}/files/{file_id}/download" response = requests.get(url, headers=headers) data = response.json() download_url = data["url"] # Downloads the file to the cwd url_resp = urllib.request.urlretrieve(download_url, "Client_API_Extract.csv.gz") file_name = url_resp[0] decrypted_file = "Client_File.csv.gz" # Base64 > Hex encryption_key = base64.b64decode(encryption_key).hex() print(encryption_key) iv = base64.b64decode(iv).hex() print(iv) # Decryption Command as provided in Northpass Documentation resp = subprocess.run( [ "openssl", "enc", "-aes-256-cbc", "-d", "-nosalt", "-in", file_name, "-out", decrypted_file, "-K", encryption_key, "-iv", iv, ] ) print(resp) # Print data in CSV to ensure it is human readable with gzip.open(decrypted_file, "rb") as uncompressed: file = uncompressed.read() print(file) if __name__ == "__main__": get_extract_id(base_url, headers, extract_id, encryption_key)