How to Create Encryption and Decryption in Python Using OOP

In today’s digital age, data security is more important than ever. One of the fundamental ways to ensure data security is through encryption and decryption. We’ll explore how to create a simple encryption and decryption program in Python using Object-Oriented Programming (OOP). This project will help you understand the basics of encryption and how OOP can be used to structure your code effectively.

Understanding Encryption and Decryption

Encryption is the process of converting plain text into a coded format that is unreadable to unauthorized users. Decryption is the reverse process, converting the encrypted data back into its original form. In this project, we’ll use a simple Caesar cipher technique, where each character in the plain text is shifted by a certain number of places down the alphabet.

Setting Up the Project

Before we dive into the code, let’s outline the steps we’ll follow:

  1. Create an Encrypt class to handle the encryption process.
  2. Create a Decrypt class that inherits from the Encrypt class to handle the decryption process.
  3. Implement methods for sending (encrypting) and receiving (decrypting) data.
  4. Test the program to ensure it works as expected.

Writing the Code

Let’s start by defining our Encrypt class. This class will have an __init__ method to initialize the necessary attributes and a sender method to handle the encryption.

class Encrypt:
    def __init__(self):
        self.send = ""
        self.res = []

    # Sender encrypts the data
    def sender(self):
        self.send = input("Enter the data: ")
        self.res = [ord(i) + 2 for i in self.send]
        print("Encrypted data:", "".join(chr(i) for i in self.res))

In the sender method, we take user input and shift each character’s ASCII value by 2. We then convert these values back to characters and print the encrypted data.

Next, we’ll create the Decrypt class, which inherits from Encrypt. This class will have a receiver method to handle the decryption.

class Decrypt(Encrypt):
    # Receiver decrypts the data
    def receiver(self):
        decrypted_data = "".join(chr(i - 2) for i in self.res)
        print("Decrypted data:", decrypted_data)

In the receiver method, we shift each character’s ASCII value back by 2 to get the original data and print it.

Finally, we’ll create an instance of the Decrypt class and call the sender and receiver methods to test our program.

obj = Decrypt()
obj.sender()
obj.receiver()

Testing the Program

When you run the program, it will prompt you to enter some data. After you enter the data, it will display the encrypted and decrypted versions. For example, if you enter “Hello”, the output might look like this:

Enter the data: Hello
Encrypted data: Jgnnq
Decrypted data: Hello

Adding More Practical Functionality

To make this project more practical, let’s add some additional features:

  1. Custom Shift Value: Allow the user to specify the shift value for encryption and decryption.
  2. File Encryption: Enable encryption and decryption of text files.
  3. User Interface: Create a simple text-based menu for user interaction.

Custom Shift Value

We’ll modify the Encrypt and Decrypt classes to accept a shift value.

class Encrypt:
    def __init__(self, shift=2):
        self.send = ""
        self.res = []
        self.shift = shift

    def sender(self):
        self.send = input("Enter the data: ")
        self.res = [ord(i) + self.shift for i in self.send]
        print("Encrypted data:", "".join(chr(i) for i in self.res))

class Decrypt(Encrypt):
    def receiver(self):
        decrypted_data = "".join(chr(i - self.shift) for i in self.res)
        print("Decrypted data:", decrypted_data)

File Encryption

We’ll add methods to read from and write to files.

class Encrypt:
    def __init__(self, shift=2):
        self.send = ""
        self.res = []
        self.shift = shift

    def sender(self):
        self.send = input("Enter the data: ")
        self.res = [ord(i) + self.shift for i in self.send]
        print("Encrypted data:", "".join(chr(i) for i in self.res))

    def encrypt_file(self, filename):
        with open(filename, 'r') as file:
            self.send = file.read()
        self.res = [ord(i) + self.shift for i in self.send]
        with open(filename + '.enc', 'w') as file:
            file.write("".join(chr(i) for i in self.res))
        print(f"File encrypted and saved as {filename}.enc")

class Decrypt(Encrypt):
    def receiver(self):
        decrypted_data = "".join(chr(i - self.shift) for i in self.res)
        print("Decrypted data:", decrypted_data)

    def decrypt_file(self, filename):
        with open(filename, 'r') as file:
            self.res = [ord(i) for i in file.read()]
        decrypted_data = "".join(chr(i - self.shift) for i in self.res)
        with open(filename + '.dec', 'w') as file:
            file.write(decrypted_data)
        print(f"File decrypted and saved as {filename}.dec")

User Interface

We’ll create a simple menu for user interaction.

def main():
    shift = int(input("Enter the shift value: "))
    obj = Decrypt(shift)

    while True:
        print("\n1. Encrypt text\n2. Decrypt text\n3. Encrypt file\n4. Decrypt file\n5. Exit")
        choice = input("Choose an option: ")

        if choice == '1':
            obj.sender()
        elif choice == '2':
            obj.receiver()
        elif choice == '3':
            filename = input("Enter the filename to encrypt: ")
            obj.encrypt_file(filename)
        elif choice == '4':
            filename = input("Enter the filename to decrypt: ")
            obj.decrypt_file(filename)
        elif choice == '5':
            break
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main()

Final Thoughts

This enhanced project demonstrates the basics of encryption and decryption using Python and OOP. By adding custom shift values, file encryption, and a user interface, we’ve made the program more practical and user-friendly. While the Caesar cipher is not secure for real-world applications, it serves as a great introduction to the concepts of data security and OOP. You can further expand this project by implementing more complex encryption algorithms or adding features like GUI integration.

Related blog posts