Merras
CyberSecurity Student
⚠️Educational purposes only!!⚠️
On this project i will show you how to create a script written in Python to encrypt files on Linux.
First of all i would like to explain whats an 'Encryption Script', An encryption script written in Python on a Unix-based system is a program that uses cryptographic techniques to convert plaintext data into an unreadable format.
Requirements needed:
- Unix-based OS (in my case it was made with Debian 12)
- Python + 3.0
- Fernet cryptographic key base64-encoded (i will explain later how to generate one with Python)
Necessary Python Modules:
- "os" module: Allows Python programs to interact with the operating system, providing functions for managing files, directories, and system processes.
- "tkinter" module: Python's standard GUI toolkit for creating graphical user interfaces (GUIs). It provides widgets and methods to build windows, buttons, input fields, etc.
- "tkinter.messagebox": A submodule of 'tkinter' for displaying standard dialogs and message boxes in GUI applications, such as alerts, warnings, errors, and confirmations.
- "threading" module: Provides tools for working with threads in Python, enabling concurrent execution of tasks within a single process. Useful for handling multiple tasks simultaneously.
- "cryptography.fernet" module: Part of the 'cryptography' library, offers symmetric encryption using the Fernet algorithm. Allows encrypting and decrypting data securely using a shared key.
- "base64" module: The 'base64' module provides functions for encoding binary data to ASCII text using Base64 encoding and decoding Base64-encoded data back to binary.
To begin with, i will explain how to create a "Fernet cryptographic key base64-encoded", First we will need a file created with 'touch' command and given execution permissions with 'chmod', once we have this we will start to write our program to generate the key:
Then we will save the generated key for it's use later on.
Once we reached this point, we will start writting our main program, (I used customized names for methods etc...) first of all we will create the method 'ejecutar_codigo(self)':
Details:
- static_key Our generated cryptographic key with fernet
- encrypted_directory Path to our desired directory to encrypt, ⚠️If we use a path like '/etc/' we will need SUDO privileges.⚠️
- codigo = self.codigo_entry.get(): Retrieves the decryption key entered by the user from some input field (codigo_entry).
- if codigo: Checks if a decryption key (codigo) is provided.
- self.codigo_ingresado = True: Sets a flag (codigo_ingresado) indicating that a decryption key has been entered.
- threading.Thread(target=self.desencriptar_archivos, args=(encrypted_directory, codigo)).start(): Starts a new thread to execute the desencriptar_archivos method, passing encrypted_directory (presumably the directory containing encrypted files) and the decryption key (codigo) as arguments. This allows decryption to occur concurrently with other operations in the application.
Now we will create the method named 'encriptar_archivos(self, directory_path, key)':
Details:
- fernet = Fernet(static_key) Initializes a Fernet object with a static encryption key (static_key). This key should ideally be kept secure and not hard-coded in production code.
- Iterates over each file (filename) in the specified directory (directory_path).
- Checks if the item is a file (os.path.isfile(filepath)).
- Reads the contents of each file (data), encrypts it using fernet.encrypt(data) , and writes the encrypted data to a new file with a '.encrypted' suffix (filepath + '.encrypted').
- Deletes the original unencrypted file (os.remove(filepath)) after successful encryption.
- Finally, removes any remaining files in the directory that are not .encrypted to ensure only encrypted files remain.
Finally we will create the last method named 'desencriptar_archivos(self, directory_path, key)':
Details:
- fernet = Fernet(key.encode()) Initializes a Fernet object with the decryption key (key), which is first encoded to bytes (key.encode()).
- Uses os.walk(directory_path) to traverse through all files (filenames) in the directory (directory_path) and its subdirectories (dirpath and dirnames).
- Checks if each file (filename) ends with .encrypted (filepath.endswith('.encrypted')), indicating it is an encrypted file.
- Reads the encrypted data from each file (encrypted_data), decrypts it using fernet.decrypt(encrypted_data), and writes the decrypted data to a new file (filepath[:-10], removing the '.encrypted' suffix).
- Deletes the original encrypted file (os.remove(filepath)) after successful decryption.
- Closes the GUI window or application (self.destroy()) after completing the decryption process.
- Displays an error message if an invalid decryption key (ValueError) is provided using messagebox.showerror().
To add some personalisation to the script we can add a custom module like i did in this example, i just simpply added a few phrases to make it look cool and an ascii art image:
Now we finished the Script lets going to test it, first of all we are going to create a file with something in it like inside of the desired encrypted directory like i did here:
Now we are going to execute the script with Python 3, remember to add execution permissions to the script:
Once we executed the script and we try to decrypt it with a wrong key we will see the next message:
If we don't decrypt the file, everything would be encrypted and we would be unable to read it:
If we decrypt it with the correct key the script will close itself and the files would be restored:
This was all! I hope you liked my script! you can get the code here: Code here