DEV Community

loading...
Cover image for How to send a secret Whats app message from terminal using Gecko Driver

How to send a secret Whats app message from terminal using Gecko Driver

Arun krishna
To explore and implement emerging trends in Information Technology. Software Developer. Very much open to new domains depending upon the work.
Updated on ・4 min read

Disclaimer:
This code is for educational purposes only and the author is not responsible for any consequences resulted. Please do not try it if you do not agree for the condition.

Hello everyone,
In this post I will be showing how I have sent an encrypted secret whatsapp message.

Prerequisites:

  • Gecko web driver
  • Python 3.X
  • pycryptodome library
  • cryptography library
  • colorama library

Firstly the architecture of the system is as shown in the below figure
Alt Text

In this post I will demonstrate with AES algorithm. Similarly you can try with different encryption algorithms. And we are going to use Gecko driver to send the message automatically. The primary goal is encrypting and communicating the sensitive data in whatsapp.The encryption of AES used here is EAX mode.

Speciality:
This mode is difficult in encryption because it doesnot use UTF-8 encoding. It utilizes Windows-1252 encoding which is difficult for any external compilers to decode the message.

Libraries:
First let's install the required libraries. Write the 3 libraries pycryptodome
cryptography
colorama
in text file named requirements.txt
Now install them using pip command

pip install -r requirements.txt

Put the Gecko driver in the directory where you are going to execute the code.
All the pre-requisites are done let's dive into the coding part

Import the libraries

import base64
import binascii
import binhex
import os
import string
import sys
from random import choice
import smtplib
import os
import hashlib

Let's display an error message if any libraries are missing

try:
    from colorama import Fore, Style, init
    from Crypto.Cipher import AES
    from Crypto.Random import random
    from cryptography.fernet import Fernet
except ImportError:
    print(
        "ERROR: Missing required libraries.\n"
        "Install dependencies with: pip install -r requirements.txt"
    )
    sys.exit(1)

colorList = [Style.BRIGHT + Fore.RED, Style.BRIGHT , Style.BRIGHT + Fore.YELLOW, Style.BRIGHT + Fore.BLUE, Fore.GREEN ,Fore.MAGENTA, Style.BRIGHT + Fore.CYAN, Style.BRIGHT + Fore.WHITE]

Here I am using colorama library to change the colours for every execution.

Let's get the required input

def get(datatype):
    try:
        (message) = {
            "plaintext": ("Enter plaintext message"),
            "encoded": ("Enter encoded message"),
            "encrypted": ("Enter encrypted message"),
            "filename": ("Specify filename"),
            "passwordfilename": ("Specify  passwordfilename"),
            "password": ("Enter encryption password"),
            "Select": ("Choose any one"),
        }[datatype]
    except KeyError:
        message = datatype
    return input(f"\n{message}: {Style.RESET_ALL}").encode()

SENDER:
In my previous post I have mentioned about Xpath and automation. We are going to use similar concept here with whatsapp too. First let us write the bot script and store it in bot.py

from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from time import sleep
import chardet

driver = webdriver.Firefox()
driver.get('http://web.whatsapp.com')
sleep(15)
driver.find_element_by_xpath("/html/body/div/div/div/div/div/div/div[1]/div/div/div[1]/div/div/div").click()
sleep(5)

fileLocation= "Path/AESKEY.txt"
with open(fileLocation,"r") as file:
    for line in file:
        driver.find_element_by_xpath("//*/footer/div[1]/div[2]/div/div[2]").send_keys(line)
        driver.find_element_by_xpath("//*/footer/div[1]/div[2]/div/div[2]").send_keys(Keys.ENTER)
sleep(5)


fileLocation= "Path/AES.txt"
with open(fileLocation,"r") as file:
    for line in file:
        for word in line.split(" "):
            driver.find_element_by_xpath("//*/footer/div[1]/div[2]/div/div[2]").send_keys(word)
            driver.find_element_by_xpath("//*/footer/div[1]/div[2]/div/div[2]").send_keys(Keys.ENTER)


# No special characters and spaces in enc


python
We are going to store the key required to decrypt the message in AESKEY.txt file and the encrypted message in AES.txt file. This bot reads the file and then sends the message. You can send some instruction message as shown below.
Alt Text

Now let's get into the encryption part.

def aes_enc_auto():
    """Encrypt with AES."""
    keypass = random_key(16)
    data = get("plaintext")
    filename = get("filename").decode()
    cipher = AES.new(keypass.encode(), AES.MODE_EAX)
    ciphertext, tag = cipher.encrypt_and_digest(data)
    with open(filename, "wb") as outfile:
        _ = [outfile.write(item) for item in (cipher.nonce, tag, ciphertext)]

    save_path='Path/Whatsapp'
    kn = "AESKEY"
    passwordfilename = os.path.join(save_path, kn+".txt") 
    with open(passwordfilename, "wt") as outfile:
        _ = [outfile.write(item) for item in (keypass)]
    print("AES encrypted message and key files are saved")
    os.system('python bot.py')
MENU_OPTIONS.append(aes_enc_auto)

First we get the plain text from the terminal and it is stored after getting encrypted. Then gecko driver comes into action and sends the content to receiver.

RECEIVER:
The above encrypted message can be decrypted by using below code.

def aes_dec_auto():
    """Decrypt with AES."""
    filename = get("filename")
    keypass = get("password")
    with open(filename, "rb") as infile:
        nonce, tag, ciphertext = [infile.read(x) for x in (16, 16, -1)]
    cipher = AES.new(keypass, AES.MODE_EAX, nonce)
    data = cipher.decrypt_and_verify(ciphertext, tag).decode()
    show("plaintext", data)
MENU_OPTIONS.append(aes_dec_auto)

Finally let's finish the main function

# Main Function
def main():
    try:
        while True:
            print(
                "\n"
                + Fore.GREEN + "Choose from the following options, or press Ctrl-C to quit:\n\n"
                + Style.RESET_ALL
            )
            for index, option in enumerate(MENU_OPTIONS, 1):
                print(Style.BRIGHT + f"{index}: {' ' if index < 10 else ''}" f"{option.__doc__}" + Style.RESET_ALL)
            choice = get("Select")
            print()
            try:
                MENU_OPTIONS[int(choice) - 1]()
            except (IndexError,UnboundLocalError):
                print("Unknown option." + Style.RESET_ALL)
            # except ValueError:
            #     print("Invalid option."+ "Enter the number of your selection."+ Style.RESET_ALL)

    except (KeyboardInterrupt,UnboundLocalError):
        print("\n{}Program Terminated\n{}Have A Nice Day{}".format(Fore.RED,Style.BRIGHT,Style.RESET_ALL))

        sys.exit(1)


if __name__ == "__main__":
    main()

In my below repository I have implemented the above concept with various hashing and encryption algorithms. Please drop a star if you like it.

GitHub logo Chitturiarunkrishna / Encryption

Explanation is available in this link

Encryption

The main aim of this project is to send an encrypted secret message.I am going to use Gecko driver which is supported by Mozilla Firefox and send the encrypted messages. For adaptability this project can even work with Selenium which supports Google chrome.

Discussion (0)